Loading data frames into a list

I am trying to load a bundle of * .Rdata into the list.

files <- paste0("name", 1:10, ".Rdata") data <- lapply(files, load) 

This creates a list in which each item has a data frame name, but nothing else.

If I redefine the files so that it contains only the first file and calls:

 load(files) 

Then it "works", but the file in the "files" is assigned to the global environment, but this is not what I would like.

I would like to get a list that in each element contains a dataframe. That way, when I do data processing, I can iterate over the list.

+6
source share
2 answers

You can try

 lapply(files, function(x) mget(load(x))) 

mget will return the value of the object (or objects) in the list. In your .Rdata files .Rdata there is only one data.frame object for each file. Thus, even get should work.

In your code

 load(files[1]) 

Objects will be found in the global environment. Suppose that the object "d1" by typing "d1" on the console, you get the value of the object. Similar

 lapply(files, load, .GlobalEnv) 

loads the object into the global environment and can be accessed by input. Your question, which, I think, should get the values ​​in the list, and this can be done with get or mget .

+7
source

Now tested, it works!

 e1 = new.env() invisible(lapply(files, load, envir = e1)) my_list = as.list(e1) 
+5
source

Source: https://habr.com/ru/post/984582/


All Articles