Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load data frames into list

Tags:

r

lapply

load

I am trying to load a bunch *.Rdata into a list.

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

This creates a list, where in each element has the name of data frame, but nothing else.

If I redefine files such that it only contains the first file, and call:

load(files)

Then is "works", but the file in 'files' is asigned to the global enviroment, which is not what I would like.

I would like to end up with a list, which in each element contains the dataframe. Such that then when I do data processing I can lapply over the list.

like image 790
Repmat Avatar asked Apr 01 '15 18:04

Repmat


People also ask

Can you store data frames in a list?

Creating a list of Dataframes. To create a list of Dataframes we use the list() function in R and then pass each of the data frame you have created as arguments to the function.

How do I add DataFrames to a list?

Using loc[] to Append The New List to a DataFrame. By using df. loc[index]=list you can append a list as a row to the DataFrame at a specified Index, In order to add at the end get the index of the last record using len(df) function.

How do I add a DataFrame to a list in R?

In order to create a list of data frames in R, we can use the list() function. Within the function, we simply have to specify all data frames that we want to include to the list separated by a comma.

How do you join DataFrames in a list?

To join a list of DataFrames, say dfs , use the pandas. concat(dfs) function that merges an arbitrary number of DataFrames to a single one.


1 Answers

You can try

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

mget will return the value of the object(or objects) in a list. In your .Rdata files, there is only a single 'data.frame' object per file. So, even get should work.

In your code,

load(files[1]) 

The objects will be found in the global environment. Suppose, the object is 'd1', by typing 'd1' on the console, you get the value of the object. The same way

lapply(files, load, .GlobalEnv)

loads the object in the global environment, and can be accessed by typing. Your question, which I guess is to get the values in a list and that can be done with get or mget.

like image 139
akrun Avatar answered Oct 05 '22 23:10

akrun