Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list of data frames into individual data frames in R [duplicate]

Tags:

I have been searching high and low for what I think is an easy solution.

I have a large data frame that I split by factors.

eqRegions <- split(eqDataAll, eqDataAll$SeismicRegion)

This now creates a list object of the data frames by region; there are 8 in total. I would like to loop through the list to make individual data frames using another name.

I can execute the following to convert the list items to individual data frames, but I am thinking that there is a loop mechanism that is fast if I have many factors.

testRegion1 <- eqRegions[[1]]

testRegion3 <- eqRegions[[3]]

I can manually perform the above and it handles it nicely, but if I have many regions it's not efficient. What I would like to do is the equivalent of the following:

for (i in 1:length(eqRegions)) {
   region[i] <- as.data.frame(eqRegions[[i]])
}

I think the key is to define region before the loop, but it keep overwriting itself and not incrementing. Many thanks.

like image 573
Bryan Butler Avatar asked May 28 '15 20:05

Bryan Butler


People also ask

How do I separate data frames in R?

Use the split() function in R to split a vector or data frame. Use the unsplit() method to retrieve the split vector or data frame.

How do I convert a list into a DataFrame in R?

Convert List to DataFrame using data. data. frame() is used to create a DataFrame in R that takes a list, vector, array, etc as arguments, Hence, we can pass a created list to the data. frame() function to convert list to DataFrame. It will store the elements in a single row in the DataFrame.

How do I split a DataFrame into multiple Dataframes in R?

To split the above Dataframe we use the split() function. The syntax of split() function is: Syntax: split(x, f, drop = FALSE, …)


2 Answers

Try

list2env(eqRegions,envir=.GlobalEnv)
like image 127
Marat Talipov Avatar answered Sep 19 '22 17:09

Marat Talipov


This should work. The name of the data.frames created will be equal to the names within eqDataAll$SeismicRegion. Anyways, this practice of populating individual data.frames is not recommended. The more I work with R, the more I love/use list.

lapply(names(eqRegions), function(x) assign(x, eqRegions[[x]], envir = .GlobalEnv))

edit: Use list2env solution posted. Was not aware of list2env function.

like image 23
Vlo Avatar answered Sep 19 '22 17:09

Vlo