从 R 中的列表中打包和解包元素

Packing and unpacking elements from list in R

我有两个与在 R 中使用列表相关的问题,我正在尝试了解如何改进我天真的解决方案。我在这里看到了关于 similar topic 的问题,但那里描述的方法没有帮助。

Q1:

MWE:

a  <- c(1:5)
b  <- "adf"
c  <- array(rnorm(9), dim = c(3,3) )

但是,如果变量的数量(上述问题中的三个,即a, b, c)是 大(假设我们有 20 个变量),那么我当前的解决方案可能不是 最好的。

这个想法在从中返回大量变量时很有用 一个函数。

Q2:

MWE:给定packedList,提取变量a、b、c

例如:给定环境中的变量 packedList,我可以如下定义 a、b 和 c:

 a <- packedList$a
 b <- packedList$b
 c <- packedList$c

但是,如果变量的数量非常大,那么我的解决方案可能会很麻烦。 - 经过一些 Google 搜索,我找到了 one solution 但我也不确定这是否是最优雅的解决方案。解决方法如下图:

 x <- packedList
 for(i in 1:length(x)){
       tempobj <- x[[i]]
       eval(parse(text=paste(names(x)[[i]],"= tempobj")))
 }

您最有可能在寻找 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"