开发者

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 acc开发者_如何学运维essing 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜