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

在R语言中将长格式数据转换为宽格式的方法求助

问题描述

原始数据格式:

Person IDTreatment code
A00001
A00002
A00003
B00002
B00012
C00003
C00015

需要将数据转换为每行对应一位患者,列数等于患者的最大治疗次数,缺失记录填充为missing,目标格式:

Patient IDTreatment 1Treatment 2Treatment 3
A000010000200003
B0000200012missing
C0000300015missing

用户尝试使用tidyr::pivot_wider未成功,寻求R语言解决方案。

解决方案

核心是先为每个患者的治疗记录生成序号,再通过pivot_wider转换,同时指定缺失值填充内容。

# 加载所需包
library(dplyr)
library(tidyr)

# 构造原始数据(如果已有数据可跳过此步)
df <- tibble(
  `Person ID` = c("A", "A", "A", "B", "B", "C", "C"),
  `Treatment code` = c("00001", "00002", "00003", "00002", "00012", "00003", "00015")
)

# 数据转换流程
result_df <- df %>%
  # 按患者分组,生成治疗序号列
  group_by(`Person ID`) %>%
  mutate(treatment_col = paste0("Treatment ", row_number())) %>%
  ungroup() %>%
  # 转换为宽表,填充缺失值为"missing"
  pivot_wider(
    id_cols = `Person ID`,
    names_from = treatment_col,
    values_from = `Treatment code`,
    values_fill = "missing"
  ) %>%
  # 重命名列匹配目标格式
  rename(`Patient ID` = `Person ID`)

# 输出结果
print(result_df)

执行上述代码后,即可得到符合要求的宽表数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:18:32