2
votes

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)

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.

2
Why not keep everything in a list to begin with?zx8754
I can keep it in a list but the for purpose I'm in right now I need them extracted. I already know how to do that and think I'm doing that right now.runningbirds
The "answer" is probably list2env, but please don't bother with that. Just keep them in a list.joran

2 Answers

3
votes

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)
-2
votes

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.