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

如何使用pivot_wider将分组统计数据转为指定双列宽格式?

解决方法

核心思路是先给每个分组内的两行数据添加1/2的索引,再基于这个索引完成宽表转换,就能得到你需要的格式:

library(tidyverse)

# 生成原始数据
set.seed(0712)
df <- tibble(group = rep(1:3, each = 2),
             scale = rep(LETTERS[1:3], 2),
             n = c(100, 100, 150, 150, 135, 135),
             mean = runif(6, 1, 5),
             sd = runif(6))

# 转换为目标宽格式
df %>%
  group_by(group) %>%
  mutate(idx = row_number()) %>% # 给每个分组内的两行编1、2序号
  ungroup() %>%
  pivot_wider(
    id_cols = group,
    names_from = idx,
    values_from = c(scale, n, mean, sd),
    names_glue = "{.value}_{idx}" # 定义列名格式:变量名_序号
  )

输出结果

# A tibble: 3 x 9
  group scale_1 scale_2   n_1   n_2 mean_1 mean_2  sd_1  sd_2
  <int> <chr>   <chr>   <dbl> <dbl>  <dbl>  <dbl> <dbl> <dbl>
1     1 A       B         100   100   2.42   2.27 0.387 0.343
2     2 C       A         150   150   4.61   4.51 0.709 0.207
3     3 B       C         135   135   4.93   3.05 0.653 0.253

原理说明

你之前用scale作为names_from,会按scale的类别(A/B/C)生成列,但每个分组只包含两个scale,因此出现大量NA。添加分组内索引后,我们是把每个分组里的两个观测横向展开,用索引作为列名后缀,配合names_glue精准控制列名格式,完全匹配你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:05:31