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

在R中按组透视数据框:指标为行、年份为列的实现

解决方案

可以通过**pivot_longer先将指标列(metric和metric_percent)转为长格式,再用pivot_wider**将年份转为列,就能得到你想要的格式:

首先加载tidyverse包:

library(tidyverse)

处理数据的完整代码:

df <- data.frame(
  year = c(2018, 2018, 2019, 2019), 
  group = c("A", "A", "B", "B"), 
  metric = c(100, 150, 150, 200), 
  metric_percent = c(0.1, 0.2,0.3, 0.4)
)

df_result <- df %>%
  # 将指标列转为长格式,拆分出指标名称和对应数值
  pivot_longer(cols = c(metric, metric_percent),
               names_to = "metric",
               values_to = "value") %>%
  # 替换指标名称为目标命名
  mutate(metric = case_when(
    metric == "metric" ~ "headcount",
    metric == "metric_percent" ~ "representation"
  )) %>%
  # 将年份转为列,按分组和指标整理数值
  pivot_wider(names_from = year,
              values_from = value)

print(df_result)

运行后输出:

# A tibble: 4 × 4
  group metric         `2018` `2019`
  <chr> <chr>           <dbl>  <dbl>
1 A     headcount       100    150  
2 A     representation   0.1    0.2
3 B     headcount       150    200  
4 B     representation   0.3    0.4

步骤说明

  • pivot_longer:把原本的metric和metric_percent两列拆分为metric(存储指标名称)和value(存储对应数值),让每个「年份-分组-指标」组合单独成一行。
  • mutate + case_when:将原始指标列名替换为你需要的headcount和representation。
  • pivot_wider:把year列的不同取值(2018、2019)转为列,每个单元格对应该分组-指标在对应年份的数值。

最终结果完全匹配你期望的格式,可直接用flextable或gt进行后续格式化。

内容的提问来源于stack exchange,提问作者Sergio Garcia Mora

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:13:14