Packing and unpacking elements from list in R
Asked Answered
S

1

12

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")))
 }
Superfecundation answered 17/5, 2015 at 4:32 Comment(1)
you can use zeallot package in r for unpacking. library(zeallot) c(a,b,c) %<-% c(1,2,3) > a [1] 1 > b [1] 2 > c [1] 3Szabadka
E
12

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"
Envoy answered 17/5, 2015 at 4:36 Comment(2)
Thanks for your answer. In the scenario where we have four variables in the environment, (say a,b,c,d) but we only want to make a list for three variables ( a,b,c) then mget(ls()) won’t work. Any thoughts on how to go around it?Superfecundation
@skaur, just supply a character vector of the values you want: mget(c("a", "b", "c")).Envoy

© 2022 - 2024 — McMap. All rights reserved.