从函数内将多个对象分配给 .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屋!