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

如何用R语言pivot longer将宽格式数据转换为指定长格式?

解决方案

可以使用tidyverse工具集里的tidyr::pivot_longer()函数完成宽格式到长格式的转换,核心是通过正则匹配拆分列名,自动映射对应字段:

# 加载必要工具包
library(tidyverse)

# 假设原始数据框名为df,替换为实际变量名即可
df_long <- df %>%
  pivot_longer(
    cols = c(mean_a, sd_a, n_a, mean_b, sd_b, n_b),
    names_pattern = "(mean|sd|n)_(a|b)",
    names_to = c(".value", "arm"),
    values_to = NULL
  )

代码说明

  • cols:指定需要转换的宽格式列范围,覆盖所有分组的均值、标准差、样本量列
  • names_pattern:用正则表达式拆分列名,(mean|sd|n)匹配指标类型,(a|b)匹配分组标识
  • names_to = c(".value", "arm"):.value表示将匹配到的第一部分(mean/sd/n)作为新列名,第二部分(a/b)作为arm列的取值

转换后结果示例

timepoints_daystimepoints_windowarmmeansdn
143a7011297
143b6911298
283a6511284
283b7311285
..................

如果不想依赖tidyverse,也可以用基础R的reshape()函数实现:

df_long <- reshape(
  df,
  varying = list(c("mean_a", "mean_b"), c("sd_a", "sd_b"), c("n_a", "n_b")),
  v.names = c("mean", "sd", "n"),
  timevar = "arm",
  times = c("a", "b"),
  direction = "long"
)
# 调整列顺序并重置行名
df_long <- df_long[, c("timepoints_days", "timepoints_window", "arm", "mean", "sd", "n")]
rownames(df_long) <- NULL

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:35:42