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

基于单列多时间诊断值创建多列:R语言数据格式转换求助

解决方法

可以用tidyverse包中的tidyr和dplyr工具完成数据格式转换,步骤如下:

  1. 先加载所需包:
library(tidyverse)
  1. 执行数据转换代码:
df_transformed <- df %>%
  # 将宽格式的诊断列转为长格式,提取时间和诊断值
  pivot_longer(cols = starts_with("diag_t"), 
               names_to = "time", 
               names_prefix = "diag_", 
               values_to = "diagnosis") %>%
  # 为每个病症生成二进制标记(1=存在该诊断,0=不存在)
  mutate(
    diag1 = ifelse(diagnosis == 1, 1, 0),
    diag2 = ifelse(diagnosis == 2, 1, 0),
    diag3 = ifelse(diagnosis == 3, 1, 0),
    diag4 = ifelse(diagnosis == 4, 1, 0)
  ) %>%
  # 移除冗余列,转回宽格式并生成目标列名
  select(-diagnosis) %>%
  pivot_wider(names_from = time, 
              values_from = c(diag1, diag2, diag3, diag4),
              names_glue = "{time}_diag{str_remove(.value, 'diag')}")
  1. 查看转换结果:
print(df_transformed)

转换后的数据会生成t1_diag1、t1_diag2……t4_diag4这类列,每个列对应某时间点下某病症的存在标记,完全符合你需要的格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:45:27