我有两个与在R中使用list相关的问题,我试图看看如何改进我天真的解决方案.我在这里看到过类似主题的问题,但那里描述的方法没有帮助.
MWE:
a <- c(1:5)
b <- "adf"
c <- array(rnorm(9), dim = c(3,3) )
Run Code Online (Sandbox Code Playgroud)
packedList <- list(a = a, b = b, c = c)
但是,如果变量的数量(上面的问题中有三个a, b, c
)很大(比如我们有20个变量),那么我目前的解决方案可能不是最好的.
从函数返回大量变量时,这个想法很有用.
MWE:给定packedList
,提取变量a,b,c
例如:给定环境中的变量packedList,我可以如下定义a,b和c:
a <- packedList$a
b <- packedList$b
c <- packedList$c
Run Code Online (Sandbox Code Playgroud)
但是,如果变量的数量非常大,那么我的解决方案可能很麻烦.- 在谷歌搜索之后,我找到了一个解决方案,但我不确定它是否也是最优雅的解决方案.解决方案如下所示:
x <- packedList
for(i in 1:length(x)){
tempobj <- x[[i]]
eval(parse(text=paste(names(x)[[i]],"= tempobj")))
}
Run Code Online (Sandbox Code Playgroud)
您最有可能寻找mget
(Q1)和list2env
(Q2).
这是一个小例子:
ls() ## Starting with an empty workspace
# character(0)
## Create a few objects
a <- c(1:5)
b <- "adf"
c <- array(rnorm(9), dim = c(3,3))
ls() ## Three objects in your workspace
[1] "a" "b" "c"
## Pack them all into a list
mylist <- mget(ls())
mylist
# $a
# [1] 1 2 3 4 5
#
# $b
# [1] "adf"
#
# $c
# [,1] [,2] [,3]
# [1,] 0.70647167 1.8662505 1.7941111
# [2,] -1.09570748 0.9505585 1.5194187
# [3,] -0.05225881 -1.4765127 -0.6091142
## Remove the original objects, keeping just the packed list
rm(a, b, c)
ls() ## only one object is there now
# [1] "mylist"
## Use `list2env` to recreate the objects
list2env(mylist, .GlobalEnv)
# <environment: R_GlobalEnv>
ls() ## The list and the other objects...
# [1] "a" "b" "c" "mylist"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3281 次 |
最近记录: |