Assign multiple objects to .GlobalEnv from within a function

纵饮孤独 提交于 2019-11-26 04:50:29

问题


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).


回答1:


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"    


来源:https://stackoverflow.com/questions/9726705/assign-multiple-objects-to-globalenv-from-within-a-function

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