从一个函数中向.GlobalEnv分配多个对象 [英] Assign multiple objects to .GlobalEnv from within a function
问题描述
前一天在这里发表的一篇文章让我想知道如何从一个函数中为全局环境中的多个对象分配值.这是我使用lapply
的尝试(assign
可能比<<-
更安全,但我从未真正使用过它,也不熟悉它).
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).
推荐答案
2018年10月10日更新:
执行此特定任务的最简洁的方法是像这样使用list2env()
:
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"
原始答案,演示了使用assign()
您说对了,assign()
是完成该任务的正确工具.其envir
参数使您可以精确控制分配的位置-<-
或<<-
均不可用的控制.
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 <<-
.
例如,要在全局环境中将X
的值分配给名为NAME
的对象,您可以这样做:
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)
在您的情况下:
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"
这篇关于从一个函数中向.GlobalEnv分配多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!