Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign multiple objects to .GlobalEnv from within a function

A post on here a day back has me wondering how to assign values to multiple objects in the global environment from within a function. This is my attempt using lapply (assign may be safer than <<- but I have never actually used it and am not familiar with it).

#fake data set df <- data.frame(   x.2=rnorm(25),   y.2=rnorm(25),   g=rep(factor(LETTERS[1:5]), 5) )  #split it into a list of data frames LIST <- split(df, df$g)  #pre-allot 5 objects in R with class data.frame() V <- W <- X <- Y <- Z <- data.frame()  #attempt to assign the data frames in the LIST to the objects just created lapply(seq_along(LIST), function(x) c(V, W, X, Y, Z)[x] <<- LIST[[x]]) 

Please feel free to shorten any/all parts of my code to make this work (or work better/faster).

like image 491
Tyler Rinker Avatar asked Mar 15 '12 19:03

Tyler Rinker


1 Answers

Update of 2018-10-10:

The most succinct way to carry out this specific task is to use list2env() like so:

## Create an example list of five data.frames df <- data.frame(x = rnorm(25),                  g = rep(factor(LETTERS[1:5]), 5)) LIST <- split(df, df$g)  ## Assign them to the global environment list2env(LIST, envir = .GlobalEnv)  ## Check that it worked ls() ## [1] "A"    "B"    "C"    "D"    "df"   "E"    "LIST" 

Original answer, demonstrating use of assign()

You're right that assign() is the right tool for the job. Its envir argument gives you precise control over where assignment takes place -- control that is not available with either <- or <<-.

So, for example, to assign the value of X to an object named NAME in the the global environment, you would do:

assign("NAME", X, envir = .GlobalEnv) 

In your case:

df <- data.frame(x = rnorm(25),                  g = rep(factor(LETTERS[1:5]), 5)) LIST <- split(df, df$g) NAMES <- c("V", "W", "X", "Y", "Z")  lapply(seq_along(LIST),         function(x) {            assign(NAMES[x], LIST[[x]], envir=.GlobalEnv)         } )  ls() [1] "df"    "LIST"  "NAMES" "V"     "W"     "X"     "Y"     "Z"     
like image 56
Josh O'Brien Avatar answered Oct 04 '22 05:10

Josh O'Brien