rbind 列表列表中的数据帧

发布于 2024-08-09 01:26:09 字数 242 浏览 2 评论 0原文

我有一个列表列表,如下所示:x[[state]][[year]]。其中的每个元素都是一个数据框,单独访问它们不是问题。

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

我知道我可以使用 do.call("rbind",list) 将单个列表合并到数据框中。但我不知道如何跨列表列表执行此操作。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

陌生 2024-08-16 01:26:09

首先将其折叠成列表:

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

Collapse it into a list first:

list <- unlist(listoflists, recursive = FALSE)
df <- do.call("rbind", list)
我ぃ本無心為│何有愛 2024-08-16 01:26:09

您可以按照以下方式执行操作(我无法测试,因为我没有这样的结构):

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

函数 extract Year 创建一个仅包含给定年份的数据帧的列表。然后你重新绑定它们...

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

可可 2024-08-16 01:26:09

我意识到我参加聚会有点晚了,但是怎么样:

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)

它看起来与 Marek 的响应类似,但避免了 sapply/lapply 组合。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文