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

如何在R中将含列表列的tibble转换为长格式?

带列表列的tibble转长格式方法

你的问题出在列表列items上,pivot_longer没法直接处理混合普通列和列表列的结构,分两步就能搞定:

  • 先展开列表列items:用tidyr::unnest()把每个列表里的数值拆成单独行,同时保留每行对应的year、revenue、cost数据。
  • 再将revenue和cost转成长格式:用pivot_longer把这两个指标列合并成“指标名称-数值”的结构。

完整代码示例

library(tidyverse)

set.seed(123)
mightyTibble <- tibble(
   year = 1:10,
   revenue = 1000*rgamma(10,2000,3000),
   cost = 100*rgamma(10,2000,3000),
   items = lapply(1:10, \(i) runif(rpois(1,6), 10, 20))
)

# 转换步骤
long_format_tibble <- mightyTibble %>%
  unnest(items) %>%
  pivot_longer(
    cols = c(revenue, cost),
    names_to = "metric",
    values_to = "value"
  )

# 查看结果
head(long_format_tibble)

运行结果示例

# A tibble: 6 × 4
   year items metric  value
  <int> <dbl> <chr>   <dbl>
1     1  14.4 revenue  658.
2     1  14.4 cost      67.2
3     1  17.4 revenue  658.
4     1  17.4 cost      67.2
5     2  14.1 revenue  684.
6     2  14.1 cost      66.8

这样处理后,既展开了列表列的所有元素,又把revenue和cost整理成了符合整洁数据标准的长格式。

内容的提问来源于stack exchange,提问作者Aku-Ville Lehtimäki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:38:21