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.
Q1:
MWE:
a <- c(1:5)
b <- "adf"
c <- array(rnorm(9), dim = c(3,3) )
- Make a list, say with name "packedList", while preserving the name of all variables.
- Current solution:
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.
Q2:
MWE: Given packedList
, extract variables a, b, c
- I would like to extract all elements in the given list (i.e. packedList) to the environment while preserving their names. This is reverse of task 1.
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")))
}