You need to enable JavaScript to run this app. R语言基于两列半唯一值生成rolling index滚动索引的实现问题
优惠活动
大模型
产品
解决方案
定价
更多

R语言基于两列半唯一值生成rolling index滚动索引的实现问题

R语言生成跨分组滚动唯一ID的实现方法

核心实现逻辑

只要满足以下两个条件任意一个,就分配新的ID:

  • 当前行的participant取值与上一行不同
  • 当前行的item取值与上一行不同
    对上述判断结果的布尔值做累加,即可得到符合要求的全局唯一item_ID。

写法1:简洁通用版(适配base R和dplyr)

base R 实现

# 示例数据
df <- data.frame("participant" = c("a", "a", "a", "a", "b", "b", "b", "b", "c", "c"), 
                 "item" = c("X", "X", "Y", "X", "X", "X", "Y", "Z", "Z", "Z"))
# 生成item_ID
df$item_ID <- cumsum(c(TRUE, df$participant[-1] != df$participant[-nrow(df)] | df$item[-1] != df$item[-nrow(df)]))

dplyr 实现(可读性更高)

library(dplyr)
df <- df %>%
  mutate(item_ID = cumsum(
    participant != lag(participant, default = first(participant)) | 
    item != lag(item, default = first(item))
  ))

写法2:保留组内块ID版

如果需要同时保留每个participant内部的item块编号,可使用分组处理的方式:

library(dplyr)
df <- df %>%
  # 按participant分组生成组内块ID
  group_by(participant) %>%
  mutate(inner_block_id = cumsum(item != lag(item, default = first(item)))) %>%
  ungroup() %>%
  # 生成全局唯一item_ID
  mutate(item_ID = match(paste(participant, inner_block_id), unique(paste(participant, inner_block_id))))

输出结果验证

两种写法最终输出的df均与预期一致:

participant item item_ID
1            a    X       1
2            a    X       1
3            a    Y       2
4            a    X       3
5            b    X       4
6            b    X       4
7            b    Y       5
8            b    Z       6
9            c    Z       7
10           c    Z       7

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 13:54:08