You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中将tibble列表转换为指定格式的data.frame?

将tibble列表转换为指定格式的data.frame

问题描述

我拥有一个以日期为名称的tibble列表,希望将其转换为data.frame,同时将单个tibble的名称作为列名。

示例输入数据

list(`2016-07-20` = structure(list(package = c("filehash", "weathermetrics"
), n = c(179L, 7L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-2L)), `2016-06-21` = structure(list(package = c("filehash", 
"weathermetrics"), n = c(159L, 6L)), class = c("tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -2L)))

显示形式:

$`2016-07-20`
# A tibble: 2 × 2
  package            n
  <chr>          <int>
1 filehash         179
2 weathermetrics     7

$`2016-06-21`
# A tibble: 2 × 2
  package            n
  <chr>          <int>
1 filehash         159
2 weathermetrics     6

期望输出格式

package    2016-07-20    2016-06-21 
1 filehash          179           159
2 weathermetrics      7             6

解决方案

方法1:使用tidyverse工具包(dplyr + purrr + tidyr)

这种方法更灵活,适合处理各tibble的package列不完全一致的场景:

library(tidyverse)

# 定义输入列表
tibble_list <- list(
  `2016-07-20` = tibble(package = c("filehash", "weathermetrics"), n = c(179L, 7L)),
  `2016-06-21` = tibble(package = c("filehash", "weathermetrics"), n = c(159L, 6L))
)

# 转换流程
result <- tibble_list %>%
  imap_dfr(~ mutate(.x, date = .y)) %>% # 为每个tibble添加日期列(即列表元素名称)
  pivot_wider(names_from = date, values_from = n) %>% # 将日期转为列名,n作为对应值
  as.data.frame() # 转换为data.frame格式

print(result)

方法2:使用base R实现

无需加载额外工具包,适合快速处理所有tibble的package列内容完全一致的简单场景:

# 定义输入列表
tibble_list <- list(
  `2016-07-20` = structure(list(package = c("filehash", "weathermetrics"), n = c(179L, 7L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L)),
  `2016-06-21` = structure(list(package = c("filehash", "weathermetrics"), n = c(159L, 6L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L))
)

# 提取所有tibble的n列,组成矩阵
n_matrix <- sapply(tibble_list, function(x) x$n)
# 设置矩阵列名为列表元素的日期名称
colnames(n_matrix) <- names(tibble_list)
# 合并package列与n矩阵,生成最终data.frame
result <- data.frame(package = tibble_list[[1]]$package, n_matrix, stringsAsFactors = FALSE)

print(result)

内容的提问来源于stack exchange,提问作者Assa Yeroslaviz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 04:55:27