Add all Environment elements to a list automatically

3

Suppose my Environment contains the following objects (dummy names):

abcd # numeric
efgh # dataframe
ijkl # matrix
mnop # character

My goal : Put them in a list automatically, without typing:

mylist<-list(abcd,efgh,ijkl,mnop)

Is there a function that can do this? More precisely, it would be the opposite of the list2env function.

    
asked by anonymous 09.10.2018 / 16:03

2 answers

1

Here's a way to solve the problem.

First I'll create an Environment with the objects described in the question.

set.seed(1234)

e <- new.env()
e$abcd <- rnorm(10)
e$efgh <- data.frame(A = letters[1:5], X = runif(5))
e$ijkl <- matrix(1:24, ncol = 3)
e$mnop <- sample(LETTERS, 10)

Now, get the objects of environment e with the function ls and then create the list of those objects with mget .

obj <- ls(envir = e)
lista <- mget(obj, envir = e)
lista
    
09.10.2018 / 17:46
1

In addition to the ls() function, you need the function get()

x <- rnorm(10)
y <- rnorm(20)
z <- rnorm(30)

Example of using get() :

objetos <- ls()
objetos[1]
# [1] "a"
get(objetos[1])
#[1]  1.5730920 -0.1325966  0.1462377 -0.8567735  1.2704741 -0.4335724
#[7] -1.0765247  0.6400620  0.2772769  0.3432856

For all environment objects in a list:

obj <- ls()
lista = as.list(sapply(obj, get))
    
09.10.2018 / 17:44