Consider the following nested list, nest
.
考虑以下嵌套列表,nest。
nest <- list(
A = list(w = 1:5, x = letters[1:5]),
B = list(y = 6:10, z = LETTERS[1:5])
)
I'd like to send all the individual variables in nest
to the global environment. That is, the lists A
and B
, and the vectors w
, x
, y
, and z
should all go to the global environment. Here are a few of my tries along with their results. Notice that all of these only send some of the variables to the global environment.
我想将nest中的所有单个变量发送到全局环境。也就是说,列表A和B以及向量w,x,y和z都应该进入全局环境。以下是我的一些尝试以及他们的结果。请注意,所有这些只会将一些变量发送到全局环境。
list2env(nest, .GlobalEnv)
ls()
# [1] "A" "B" "nest"
list2env(unlist(nest, recursive = FALSE), .GlobalEnv)
ls()
# [1] "A.w" "A.x" "B.y" "B.z" "nest"
lapply(nest, list2env, envir = .GlobalEnv)
ls()
# [1] "nest" "w" "x" "y" "z"
with(nest, list2env(mget(ls()), .GlobalEnv))
ls()
# [1] "A" "B" "nest"
I also tried other recursive possibilities and got errors because when list2env
hits the bottom of the list, it finds that x
is not a list.
我还尝试了其他递归的可能性并得到了错误,因为当list2env命中列表的底部时,它发现x不是列表。
rapply(nest, list2env, envir = .GlobalEnv)
# Error in (function (x, envir = NULL, parent = parent.frame(),
# hash = (length(x) > : first argument must be a named list
with(nest, {
obj <- mget(ls())
do.call(list2env, c(obj, envir = .GlobalEnv))
})
# Error in (function (x, envir = NULL, parent = parent.frame(),
# hash = (length(x) > : unused arguments (A = list(w = 1:5,
# x = c("a", "b", "c", "d", "e")), B = list(y = 6:10,
# z = c("A", "B", "C", "D", "E")))
How can I recursively call list2env
so that all variables go to the global environment? From a fresh R session, ls()
would result in
如何递归调用list2env以便所有变量都转到全局环境?从一个新的R会话,ls()将导致
# [1] "A" "B" "nest" "w" "x" "y" "z"
I've also experimented with local
and am having the same problem.
我也尝试了本地,我遇到了同样的问题。
1 个解决方案
#1
7
Use a recursive function. Not elegant but it appears to work:
使用递归函数。不优雅,但似乎工作:
nest <- list(A = list(w = 1:5, x = letters[1:5]),
B = list(y = 6:10, z = LETTERS[1:5]))
test <- function(x) {
if(is.list(x)) {
list2env(x, envir = .GlobalEnv)
lapply(x, test)
}
}
test(nest)
ls()
# [1] "A" "B" "nest" "test" "w" "x" "y" "z"
#1
7
Use a recursive function. Not elegant but it appears to work:
使用递归函数。不优雅,但似乎工作:
nest <- list(A = list(w = 1:5, x = letters[1:5]),
B = list(y = 6:10, z = LETTERS[1:5]))
test <- function(x) {
if(is.list(x)) {
list2env(x, envir = .GlobalEnv)
lapply(x, test)
}
}
test(nest)
ls()
# [1] "A" "B" "nest" "test" "w" "x" "y" "z"