bshor
bshor

Reputation: 5049

rbind dataframes in a list of lists

I have a list of lists that looks like this: x[[state]][[year]]. Each element of this is a data frame, and accessing them individually is not a problem.

However, I'd like to rbind data frames across multiple lists. More specifically, I'd like to have as output as many dataframes as I have years, that is rbind all the state data frames within each year. In other words, I'd like to combine all my state data, year by year, into separate data frames.

I know that I can combine a single list into a data frame with do.call("rbind",list). But I don't know how I can do so across lists of lists.

Upvotes: 31

Views: 29994

Answers (3)

Jeroen Gilis
Jeroen Gilis

Reputation: 1

I realize I'm a bit late to the party, but what about:

mymat <- do.call(rbind, lapply(mylist, function(element){
  element[[1]] # if df is the 1st entry of each list, could also access by name
}))
mydf <- as.data.frame(mymat)

It looks similar to the response of Marek, but avoids the sapply/lapply combo.

Upvotes: 0

datanalytics.com
datanalytics.com

Reputation: 996

You can do something along the following lines (I could not test as I have no such structure):

extract.year <- function(my.year) lapply(x, function(y) y[[my.year]])

x.by.year <- sapply(my.list.of.years, function(my.year)
    do.call(rbind, extract.year(my.year)))   

The function extract year creates a list containing just the dataframes for the given year. Then you rbind them...

Upvotes: 12

hadley
hadley

Reputation: 103898

Collapse it into a list first:

list <- unlist(listoflists, recursive = FALSE)
df <- do.call("rbind", list)

Upvotes: 52

Related Questions