This question already has answers here:
How to number/label data-table by group-number from group_by?

(6 个回答)


5年前关闭。




我有以下数据框:
> test = data.frame(A = sample(1:5, 10, replace = T)) %>% arrange(A)
> test

   A
1  1
2  1
3  1
4  2
5  2
6  2
7  2
8  4
9  4
10 5

我现在希望每一行都有一个 ID,该 ID 仅在 A 的值更改时增加。这是我尝试过的:
> test = test %>% mutate(id = as.numeric(rownames(test))) %>% group_by(A) %>% mutate(id = min(id))
> test

       A    id
   (int) (dbl)
1      1     1
2      1     1
3      1     1
4      2     4
5      2     4
6      2     4
7      2     4
8      4     8
9      4     8
10     5    10

但是,我想得到以下信息:
       A    id
   (int) (dbl)
1      1     1
2      1     1
3      1     1
4      2     2
5      2     2
6      2     2
7      2     2
8      4     3
9      4     3
10     5     4

最佳答案

library(dplyr)

test %>% mutate(id = dense_rank(A))

关于r - R 数据帧中的增量 ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35370165/

10-12 17:19
查看更多