Converting a list of data frames to individual data frames in R

I searched high and low for what, in my opinion, is a simple solution.

I have a large data frame, which I share by factors.

eqRegions <- split(eqDataAll, eqDataAll$SeismicRegion)

Now an object of the list of data frames by region is created; only 8. I would like to scroll through the list to make separate data frames using a different name.

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

testRegion1 <- eqRegions[[1]]

testRegion3 <- eqRegions[[3]]

I can manually do the above, and it handles it perfectly, but if I have many regions, it is inefficient. I would like to do the following:

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

I think the key is to define the area before the loop, but it continues to rewrite itself and not enlarge. Thank you very much.

+6
source share
5 answers

Try list2env(eqRegions,envir=.GlobalEnv)

+17
source

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

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

Edit: Use list2env solution. I did not know about the list2env function.

+3
source

attach(eqRegions) should be enough. But I recommend working with them in a list form using lapply . I guarantee that this will simplify the code.

+3
source

Alternatively, β€œbest practice” when splitting data like this is to save the data in a frame, as provided by split . To process it, you use either one of sapply or lapply (many factors), and then return the result to the list. For instance:

 eqRegionsProcessed <- lapply(eqRegions, function(df) { ## do something meaningful here }) 

This obviously only works if you do the same for every data.frame file.

If you really have to break them down and deal with each data.frame uniquely, then the answers of @MatthewPlourde and @MaratTalipov will work.

+1
source

list2env returns data frames to a global environment whose names are the names in the list. An alternative if you want to have the same name for data frames, but identified by me from the loop:

 for (i in 1:length(eqRegions)) { assign(paste0("eqRegions", i), as.data.frame(eqRegions[[i]])) } 

This can be slow if the length, if the list is too long.

+1
source

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


All Articles