Packing and unpacking items from a list in R
I have two questions related to using a list in R and I am trying to figure out how I can improve my naive solution. I've seen questions on a similar topic here, but the approach described there doesn't help.
Q1:
MWE:
a <- c(1:5)
b <- "adf"
c <- array(rnorm(9), dim = c(3,3) )
- Make a list, say, named "packed list" while keeping the name of all variables.
- Current solution:
packedList <- list(a = a, b = b, c = c)
However, if the number of variables (three of the problems above, i.e. a, b, c
) is large (say we have 20 variables), then my current solution may not be the best.
This idea is useful when returning a large number of variables from a function.
Q2:
MWE: given packedList
, extract variables a, b, c
- I would like to highlight all of the items in a specified list (i.e. packageList) into the environment while keeping their names. This is inverse problem 1.
For example: given variable packageList in environment, I can define a, b and c like this:
a <- packedList$a
b <- packedList$b
c <- packedList$c
However, if the number of variables is very large, then my solution can be cumbersome. - After some googling I found one solution , but I'm not sure if this is the most elegant solution. The solution is shown below:
x <- packedList
for(i in 1:length(x)){
tempobj <- x[[i]]
eval(parse(text=paste(names(x)[[i]],"= tempobj")))
}
source to share
You are most likely looking for mget
(Q1) and list2env
(Q2).
Here's a small example:
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"
source to share