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

R语言如何将两列数据堆叠合并为一个更长的新列?

R实现两列数据堆叠为长列的方法

方法1:tidyverse 套件实现(逻辑清晰易理解)

首先构造你的示例数据:

df <- data.frame(
  Id = c(1, 2),
  Age = c(14, 28)
)

用pivot_longer做长表转换,再调整Id列的取值即可:

library(tidyverse)

result <- df %>%
  # 将所有列转为长表格式
  pivot_longer(cols = everything(), values_to = "new column") %>%
  # 仅保留原Id列对应的Id值,Age列对应的Id置空
  mutate(Id = ifelse(name == "Id", Id, NA)) %>%
  select(Id, `new column`)

# 若需要Id列的NA显示为空白,可加这一步
result$Id <- ifelse(is.na(result$Id), "", result$Id)

方法2:base R 实现(无需加载第三方包)

直接拼接两列的取值,手动构造结果表:

# 拼接两列值作为新列
new_col <- c(df$Id, df$Age)
# 原Id值加对应数量的空值作为新Id列
Id_col <- c(df$Id, rep(NA, nrow(df)))
# 构造结果表
result <- data.frame(Id = Id_col, `new column` = new_col, check.names = FALSE)
# 替换NA为空白
result$Id <- ifelse(is.na(result$Id), "", result$Id)

两种方法运行后得到的result就是你需要的输出效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:06:01