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

如何将R数据框每行重复并紧跟原行,同时新增对应标识变量

R 实现每行重复并新增标识列的方案

方法1:tidyverse 简洁实现

无需手动处理行索引,代码可读性高:

# 加载依赖包
library(tidyverse)

# 构造原始数据
df <- data.frame(a = c(1,2,3), b = c(1,2,3))

# 生成目标数据
df_res <- df %>%
  mutate(type = list(c("origin", "destination"))) %>%
  unnest(type)

方法2:base R 无依赖实现

无需安装第三方包,适合轻量场景:

# 构造原始数据
df <- data.frame(a = c(1,2,3), b = c(1,2,3))

# 按每行重复2次的规则生成新数据集
df_res <- df[rep(seq_len(nrow(df)), each = 2), ]
# 新增标识列
df_res$type <- rep(c("origin", "destination"), times = nrow(df))
# 重置行号(可选,清除重复的原行索引)
rownames(df_res) <- NULL

两种方案输出的结果都完全匹配需求的目标格式,所有重复行紧跟对应原行,标识变量顺序正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:06:01