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

R语言wide table转long table:含指标上下限的宽表转换方法咨询

解决方法

你可以使用tidyr的pivot_longer函数实现这个转换,适配带规则后缀的宽表转换需求,具体实现代码如下:

步骤1:加载依赖包、构造测试数据

# 未安装依赖先执行:install.packages("tidyverse")
library(tidyverse)

# 导入你的样本数据
df <- structure(list(cutoff = c("2017-01-01", "2017-04-01", "2017-07-01"), 
                     KM = c(2.1, 3.5, 3.7), 
                     KM_lo = c(1.4, 2.1, 2.8), 
                     KM_hi = c(4.9, 4.7, 4.2), 
                     rstm = c(7.2, 8.9, 7.2), 
                     rstm_lo = c(3.9, 6.6, 6.2),
                     rstm_hi = c(10.2, 10.8, 8.4)), 
                row.names = c(NA, -3L), 
                class = c("tbl_df", "tbl", "data.frame"))

步骤2:执行宽转长操作

df_long <- df %>%
  # 除cutoff列外,其余列全部参与转换
  pivot_longer(cols = -cutoff,
               # 按第一个下划线拆分原列名,前半部分存为VAR列,后半部分作为新列名
               names_sep = "_",
               names_to = c("VAR", ".value")) %>%
  # 重命名列匹配目标格式
  rename(Val = `<NA>`,
         `Val-lo` = lo,
         `Val-hi` = hi) %>%
  # 调整列顺序和目标输出一致
  select(cutoff, VAR, Val, `Val-hi`, `Val-lo`)

输出结果

打印df_long即可得到目标格式:

# A tibble: 6 × 5
  cutoff     VAR     Val `Val-hi` `Val-lo`
  <chr>      <chr> <dbl>    <dbl>    <dbl>
1 2017-01-01 KM      2.1      4.9      1.4
2 2017-01-01 rstm    7.2     10.2      3.9
3 2017-04-01 KM      3.5      4.7      2.1
4 2017-04-01 rstm    8.9     10.8      6.6
5 2017-07-01 KM      3.7      4.2      2.8
6 2017-07-01 rstm    7.2      8.4      6.2

可按需筛选对应行使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:54:04