从函数中为.GlobalEnv分配多个对象

时间:2021-08-08 23:22:31

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

这一天发布的帖子让我想知道如何在函数中为全局环境中的多个对象赋值。这是我尝试使用lapply(assign可能比< <更安全 - 但我从未实际使用它并且不熟悉它)。< p>

#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 个解决方案

#1


25  

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

你是对的,assign()是这项工作的正确工具。它的envir参数使您可以精确控制分配发生的位置 - < - 或<< - 无法实现的控制。

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

因此,例如,要将X的值分配给全局环境中名为NAME的对象,您将执行以下操作:

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

In your case:

在你的情况下:

df <- data.frame(
    x.2=rnorm(25),
    y.2=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"    

#1


25  

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

你是对的,assign()是这项工作的正确工具。它的envir参数使您可以精确控制分配发生的位置 - < - 或<< - 无法实现的控制。

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

因此,例如,要将X的值分配给全局环境中名为NAME的对象,您将执行以下操作:

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

In your case:

在你的情况下:

df <- data.frame(
    x.2=rnorm(25),
    y.2=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"