将通用功能应用于所有数据帧并返回具有相同名称的数据帧 [英] Apply common function to all data frames and return data frames with same name

查看:79
本文介绍了将通用功能应用于所有数据帧并返回具有相同名称的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将函数应用于R中的全局环境中的所有相似拼写的数据帧.我想将此函数应用于所有这些数据帧,但是如果不指定我就无法弄清楚该如何做一一一.我想用以前的拼写方式将数据框返回到全局环境.

I'm trying to apply a function to all similarly spelled data frames in my global environment in R. I want to apply this function to all these data frames, but I can't figure out how to do it without me specifying 1 by 1. I want to return the data frame to the global environment with the same spelling as it was before.

mtcars_test = mtcars
iris_test = iris
#....etc......could be 2 of them or 88 of them...but they will all end in "_test"

# figure out what data frames I am working with
list_of_my_dfs = lapply(ls(pattern = "*_test"), get)

#my function just multiples everything by 2
mytest_function = function(df){ df = df*2; return(df)}

helpme_return_these_dfs_to_outside_the_list=plyr::llply(list_of_my_dfs, mytest_function)

这是我需要帮助的地方.我想将函数应用于列表中的每个数据框,然后将数据框从该列表返回"到我的环境中.因此,mtcars_test和所有其他数据帧将在任何地方都乘以2,然后返回全局环境.

This is where I need help. I want to apply my function to each data frame within the list AND then 'return' the data frame from that list to my environment. So mtcars_test and all other data frames will be multiplied by 2 everywhere and returned back to global environment.

推荐答案

1)环境下标e设置为包含数据框的环境,然后获取其名称并对其进行遍历,如图所示:

1) environment subscripting Set e to the environment containing the data frames and then get their names and loop over them as shown:

BOD_test <- BOD  # not all columns of iris are numeric so use BOD instead
mtcars_test <- mtcars

e <- .GlobalEnv
nms <- ls(pattern = "_test$", envir = e)
for(nm in nms) e[[nm]] <- mytest_function(e[[nm]])

1a)分配最后一个语句的替代方法是:

1a) assign An alternative to the last statement would be:

for(nm in nms) assign(nm, mytest_function( get(nm, e) ), e)

2)列表,您可能希望将数据框保留在列表中:

2) lists You might want, instead, to keep the data frames in a list:

L <- sapply(nms, get, envir = e, simplify = FALSE)
L[] <- lapply(L, mytest_function)

2a),或者如果您不想覆盖L,则:

2a) sapply or if you do not want to overwrite L then:

sapply(L, mytest_function, simplify = FALSE)

这篇关于将通用功能应用于所有数据帧并返回具有相同名称的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆