Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Packing and unpacking elements from list in R

Tags:

list

r

packing

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")))
 }
like image 200
skaur Avatar asked May 17 '15 04:05

skaur


1 Answers

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"
like image 84
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 27 '22 23:09

A5C1D2H2I1M1N2O1R2T1