I have two questions related to using list in R and I am trying to see how I can improve my naive solution. I have seen questions on similar topic here but the approach described there is not helping.
MWE:
a <- c(1:5)
b <- "adf"
c <- array(rnorm(9), dim = c(3,3) )
packedList <- list(a = a, b = b, c = c)
However, if the number of variables (three in above problem i.e. a, b, c
) is
large (say we have 20 variables), then my current solution may not be
the best.
This is idea is useful while returning large number of variables from a function.
MWE: Given packedList
, extract variables a, b, c
For example: Given variable packedList in the environment, I can define a, b, and c as follows:
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 Google search, I found one solution but I am not sure if it is the most elegant solution either. The solution is shown below:
x <- packedList
for(i in 1:length(x)){
tempobj <- x[[i]]
eval(parse(text=paste(names(x)[[i]],"= tempobj")))
}
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With