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

如何在Tibble中对多列Pivot Longer并计算统计量?

R语言数据框长格式转换与统计量计算

原始数据

首先定义目标数据框:

df <- structure(list(uniqueID = c(1234L, 8321L, 4592L, 6166L, 9801L, 9733L, 2103L, 2108L), 
                     treatment = c("treatment_desc", "another_way", "text_to_describe", "im_a_treatment", "treatment_five", "more_text_tr", "signaling", "or_not_tr"), 
                     some_text_bin = c(0L, 1L, 1L, 0L, 1L, 0L, 0L, 0L), 
                     other_string_bin = c(1L, 1L, 1L, NA, 1L, 1L, 0L, 0L), 
                     words_bin = c(0L, NA, 0L, 1L, 0L, 1L, 0L, 1L), 
                     something_else_bin = c(0L, 1L, 0L, 0L, 0L, 0L, NA, 0L)), 
                class = "data.frame", row.names = c(NA, -8L))

数据展示:

uniqueID        treatment some_text_bin other_string_bin words_bin something_else_bin
1     1234   treatment_desc             0                1         0                  0
2     8321      another_way             1                1        NA                  1
3     4592 text_to_describe             1                1         0                  0
4     6166   im_a_treatment             0               NA         1                  0
5     9801   treatment_five             1                1         0                  0
6     9733     more_text_tr             0                1         1                  0
7     2103        signaling             0                0         0                 NA
8     2108        or_not_tr             0                0         1                  0

需求说明

需要将数据转换为长格式,最终包含uniqueID、treatment、new_column(原_bin列名)、mean(均值)、sd(标准差)、n(非缺失值计数),每个uniqueID-treatment-new_column组合对应一行统计结果。

基于group_modify的优化方案

你倾向的group_modify方案可以调整为以下形式,直接在分组内遍历所有_bin列,生成对应统计量:

library(tidyverse)

df_result <- df %>%
  group_by(treatment, uniqueID) %>%
  group_modify(function(.x, .y) {
    # 提取所有_bin类型的列
    bin_columns <- .x %>% select(ends_with("_bin"))
    # 遍历每个列计算统计量
    map_dfr(names(bin_columns), function(col_name) {
      col_values <- bin_columns[[col_name]]
      tibble(
        new_column = col_name,
        mean = mean(col_values, na.rm = TRUE),
        sd = sd(col_values, na.rm = TRUE),
        n = sum(!is.na(col_values))
      )
    })
  }) %>%
  ungroup() %>%
  # 调整列顺序匹配需求格式
  select(uniqueID, treatment, new_column, mean, sd, n)

补充方案:先转长格式再统计

如果觉得group_modify逻辑偏复杂,也可以先将数据转为长格式,再分组计算统计量,逻辑更直观:

library(tidyverse)

df_result <- df %>%
  # 先把所有_bin列转为长格式
  pivot_longer(cols = ends_with("_bin"),
               names_to = "new_column",
               values_to = "value") %>%
  # 按treatment和new_column分组计算
  group_by(treatment, new_column, uniqueID) %>%
  summarize(
    mean = mean(value, na.rm = TRUE),
    sd = sd(value, na.rm = TRUE),
    n = sum(!is.na(value))
  ) %>%
  ungroup() %>%
  select(uniqueID, treatment, new_column, mean, sd, n)

结果说明

运行上述代码后,会生成符合需求的长格式数据。注意:当单个分组的非缺失值n=1时,标准差sd会返回NA,这是因为单个数值无法计算标准差,属于正常现象。

内容的提问来源于stack exchange,提问作者C.Robin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:01:07