R数据帧中的增量ID [英] Incremental IDs in a R data frame
本文介绍了R数据帧中的增量ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据框:
> 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
I现在希望每一行都有一个ID只有当A值更改时才会增加。这是我试过的:
I now want every row to have an ID that is only incremented when the value of A changes. This is what I have tried:
> 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
但是,我想得到以下内容:
However, I would like to get the following:
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数据帧中的增量ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文