【问题标题】:adding a unique index id for the stacked rows in r为 r 中的堆叠行添加唯一索引 id
【发布时间】:2025-12-27 17:10:16
【问题描述】:

我正在尝试为相同的 id 行添加一个唯一的索引 id 变量。这是我的数据集的快照。

id <- c(1234, 1234, 2241,2241, 1252,1252,1252)
step <- c(0,0,0,0,0,1,-1)

data <- data.frame(id, step)

> data
    id step
1 1234    0
2 1234    0
3 2241    0
4 2241    0
5 1252    0
6 1252    1
7 1252   -1

所以唯一的索引 id 应该是这样的:

> data
    id step  index
1 1234    0   1
2 1234    0   1
3 2241    0   2
4 2241    0   2
5 1252    0   3
6 1252    1   3
7 1252   -1   3

【问题讨论】:

    标签: r dataframe indexing


    【解决方案1】:

    我们可以从base R使用match

    data$index <- with(data, match(id, unique(id)))
    data$index
    #[1] 1 1 2 2 3 3 3
    

    【讨论】:

      【解决方案2】:

      另一个base解决方案:

      transform(data, index=as.numeric(factor(id, levels = unique(id))))
      
      #     id step index
      # 1 1234    0     1
      # 2 1234    0     1
      # 3 2241    0     2
      # 4 2241    0     2
      # 5 1252    0     3
      # 6 1252    1     3
      # 7 1252   -1     3
      

      【讨论】:

        【解决方案3】:

        这是data.table 解决方案:

        library(data.table)
        setDT(data)[, index := .GRP, by = id]
        
        data
        #         id step index
        #    1: 1234    0     1
        #    2: 1234    0     1
        #    3: 2241    0     2
        #    4: 2241    0     2
        #    5: 1252    0     3
        #    6: 1252    1     3
        #    7: 1252   -1     3
        

        【讨论】: