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

如何在R语言中按列扩展数据框并添加行移位后的数据?

嘿,这就帮你搞定按列扩展数据框并添加行移位数据的需求!

解决方案:按列扩展数据框并添加行移位数据

首先,我先把你给出的示例数据补全成一个可运行的完整版本(方便后续演示):

df <- structure(list(
  SubjectID = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), 
                       .Label = c("1", "2", "3"), class = "factor"),
  EventNumber = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), 
                          .Label = c("1", "2"), class = "factor"),
  EventType = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L),
                        .Label = c("A", "B"), class = "factor"),
  Value = c(10, 20, 30, 40, 50, 60, 70, 15, 25, 35, 45, 55, 65, 75, 85, 95, 12, 22, 32, 42, 52, 62, 72, 82)
), class = "data.frame", row.names = c(NA, -24L))

核心思路

我们需要按SubjectID和EventNumber分组,确保行移位只在同一受试者的同一事件组内进行,然后用lag()(取前一行数据)或lead()(取后一行数据)生成新列,绑定到原数据框中。

单列移位示例

用dplyr包实现最简洁:

library(dplyr)

# 扩展数据框,添加Value列的前一行、后一行数据作为新列
df_expanded <- df %>%
  group_by(SubjectID, EventNumber) %>%
  mutate(
    Value_prev = lag(Value, 1),  # 存储当前行的前一行Value值
    Value_next = lead(Value, 1)  # 存储当前行的后一行Value值
  ) %>%
  ungroup()

# 查看前10行结果
head(df_expanded, 10)

运行后你会看到,每个分组内的第一行Value_prev是NA(没有前一行),最后一行Value_next是NA(没有后一行),完全符合预期。

多列批量移位示例

如果需要对多个列(比如EventType和Value)同时生成移位列,可以用across()批量处理:

df_expanded_multi <- df %>%
  group_by(SubjectID, EventNumber) %>%
  mutate(
    # 对指定列生成前一行的移位列,命名规则为「原列名_prev」
    across(c(EventType, Value), ~lag(., 1), .names = "{col}_prev"),
    # 对指定列生成后一行的移位列,命名规则为「原列名_next」
    across(c(EventType, Value), ~lead(., 1), .names = "{col}_next")
  ) %>%
  ungroup()

这样一次性就能生成所有需要的移位列,非常高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:32:52