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

使用R按预设条件将宽数据框转换为长数据框

R数据框宽转长格式实现方案

首先将你的原始数据框赋值给变量df:

df <- structure(list(study_id = structure(c(1, 3, 4), label = "Subject Study ID"), 
    creatinine1 = structure(c(82, 140, 88), label = "Baseline Creatinine"), 
    creatinine2 = structure(c(90, 122, 125), label = "Creatinie level: 3 months"), 
    egfr1 = structure(c(85, 42, 75), label = "Baseline eGFR "), 
    egfr2 = structure(c(73, 50, 50), label = "eGFR levels : 3 months"), 
    treat = structure(c(1L, 2L, 2L), levels = c("Active", "Placebo"
    ), class = "factor")), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame"))

使用tidyverse工具链完成格式转换:

library(tidyverse)

result_df <- df %>%
  # 将指标列转为长格式,保留分组列
  pivot_longer(cols = -c(study_id, treat), names_to = "name", values_to = "value") %>%
  # 拆分列名:分离生物标志物名称和时间后缀(1/2)
  separate(name, into = c("biomarker", "time"), sep = "(?=\\d)", convert = TRUE) %>%
  # 映射时间后缀为目标列名,同时统一treat列大小写
  mutate(
    time = case_when(
      time == 1 ~ "baseline",
      time == 2 ~ "three_months"
    ),
    treat = tolower(as.character(treat))
  ) %>%
  # 转回宽格式,匹配目标结构
  pivot_wider(names_from = time, values_from = value) %>%
  # 调整生物标志物名称首字母大写
  mutate(biomarker = str_to_title(biomarker)) %>%
  # 调整列顺序与目标一致
  select(study_id, biomarker, baseline, three_months, treat)

# 查看最终结果
print(result_df)

关键步骤说明

  • pivot_longer:先把宽格式的多指标列转为长格式,便于拆分列名
  • separate:通过正则表达式(?=\\d)(正向预查数字)拆分列名,自动区分生物标志物前缀和时间后缀
  • case_when:将数字后缀1/2映射为目标列名baseline/three_months
  • pivot_wider:将长格式数据转回所需的宽格式,每个生物标志物对应一行数据
  • 最后调整文本格式和列顺序,完全匹配目标结构

运行后输出结果:

# A tibble: 6 × 5
  study_id biomarker baseline three_months treat  
     <dbl> <chr>        <dbl>        <dbl> <chr>  
1        1 Creatinine      82           90 active  
2        1 eGFR            85           73 active  
3        3 Creatinine     140          122 placebo 
4        3 eGFR            42           50 placebo 
5        4 Creatinine      88          125 placebo 
6        4 eGFR            75           50 placebo 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:24:27