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

如何在R中使用dplyr将多列高程数据转换为单列长表?

R宽高程表转单列存储实现方案(dplyr/tidyverse)

实现代码

使用tidyr提供的pivot_longer函数即可完成需求,这也是目前tidyverse生态中官方推荐的长/宽表转换函数,替代旧版的gather函数:

library(tidyverse)

df <- df %>%
  pivot_longer(
    # 选中所有需要转换的高程列,也可写作 cols = -ID 即排除ID列外所有列
    cols = starts_with("Elevation"),
    # 不需要保留原高程列名(Elevation_1/2/3/4),因此设为NULL
    names_to = NULL,
    # 转换后的高程值统一存入Elevation列
    values_to = "Elevation"
  )

补充说明

如果你习惯使用旧版gather函数,正确写法如下:

df <- df %>%
  # 排除ID列,其余列转换为长表,原列名存入elev_col、值存入Elevation
  gather(key = "elev_col", value = "Elevation", -ID) %>%
  # 删除不需要的原列名列
  select(-elev_col)

你之前写的gather(ID)存在参数错误,是把ID列也纳入了转换范围,因此无法得到预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:06:02