Automatically add all Environment elements to a list

Asked

Viewed 64 times

3

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

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

My goal: put them in a list automatically without having to write:

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

Is there a function able to perform this? More precisely, it would be the opposite of the function list2env.

  • There is yes, see the function ls().

  • I tried several actions (including with ls), but only the names of the objects enter the list. I want the objects themselves to be in the list.

  • 1

    So you must be looking for get, when it is only one object, and mget for various objects.

2 answers

1

Beyond the function ls(), you need the function get()

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

Example of the use of 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))

1


Here’s a way to solve the problem.

First I will 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, you get the Nvironment objects e with the function ls and then create the list of these objects with mget.

obj <- ls(envir = e)
lista <- mget(obj, envir = e)
lista

Browser other questions tagged

You are not signed in. Login or sign up in order to post.