Apply common function to all data frames and return data frames with same name

天大地大妈咪最大 提交于 2019-12-01 10:49:51

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) assign An alternative to the last statement would be:

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

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) sapply or if you do not want to overwrite L then:

sapply(L, mytest_function, simplify = FALSE)

You can use eapply to iterate over an environment and then assign to store an object to your global environment. The function argument to eapply will be an anonymous function which first gets the df from global, assigning it to a temp variable, pass it to your function and then use assign to put it back to global.

I'd show you the code, but if you can't code this yourself you really shouldn't be doing it.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!