简体   繁体   中英

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.

Collapse it into a list first:

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

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM