list rbind 列表中的数据帧

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1652522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:24:44  来源:igfitidea点击:

rbind dataframes in a list of lists

listrdataframe

提问by bshor

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.

我有一个列表的列表,看起来像这样:x[[state]][[year]]。其中的每个元素都是一个数据框,单独访问它们不是问题。

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.

但是,我想在多个列表中绑定数据框。更具体地说,我希望输出尽可能多的数据帧,即 rbind 每年内的所有状态数据帧。换句话说,我想将我所有的州数据逐年合并到单独的数据框中。

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.

我知道我可以将单个列表与do.call("rbind",list). 但我不知道如何跨列表执行此操作。

采纳答案by datanalytics.com

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

函数提取年份创建一个列表,其中仅包含给定年份的数据框。然后你绑定他们...

回答by hadley

Collapse it into a list first:

先把它折叠成一个列表:

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