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

R语言如何将每行的相邻观测值配对生成新行并保留id?

R语言tibble相邻观测值配对实现方案

本方案适配任意数量的x类列,你有50个x列也可以直接复用,无需修改核心逻辑。

完整实现代码(tidyverse生态,适配tibble操作习惯)

首先补全示例中缺失的y列定义,再运行处理逻辑即可:

# 加载依赖包
library(tidyverse)

# 构造示例数据
y <- 1:10
x1 <- c("cook", "clean", "wash", "walk", "wish", "broom", "clean", "wash", "walk", "cook")
x2 <- c("move", "climb", "skate", "ball", "climb", "jog", "job", "skate", "ball", "climb")
x3 <- c("try", "clean", "boom", "walk", "bring", "broom", "sing", "wash", "jump", "fly")
df <- tibble(y, x1, x2, x3)

# 核心处理逻辑
res <- df %>%
  group_by(y) %>%
  # 选择除y外的所有列做长宽转换,50个x列也无需修改该行
  pivot_longer(cols = -y, names_to = "col", values_to = "val") %>%
  mutate(next_val = lead(val)) %>%
  filter(!is.na(next_val)) %>%
  ungroup() %>%
  # 可根据需求自定义输出列名
  select(y, from = val, to = next_val)

输出验证

运行后前4行结果完全匹配预期:

# A tibble: 20 × 3
       y from  to   
   <int> <chr> <chr>
 1     1 cook  move 
 2     1 move  try  
 3     2 clean climb
 4     2 climb clean

基础R实现方案(无需加载第三方包)

如果不想用tidyverse,可以用基础R实现,同样支持任意数量的x列:

n_xcols <- ncol(df) - 1
pair_list <- lapply(1:(n_xcols - 1), function(i) {
  out <- df[, c(1, i+1, i+2)]
  colnames(out) <- c("y", "from", "to")
  out
})
res <- do.call(rbind, pair_list)
res <- res[order(res$y), ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:15:02