R数据帧中的增量ID

ase*_*pel 4 r dplyr

我有以下数据框:

> 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
Run Code Online (Sandbox Code Playgroud)

我现在希望每一行都有一个只在A的值改变时才增加的ID.这是我尝试过的:

> 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
Run Code Online (Sandbox Code Playgroud)

但是,我想得到以下内容:

       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
Run Code Online (Sandbox Code Playgroud)

dav*_*ers 6

library(dplyr)

test %>% mutate(id = dense_rank(A))
Run Code Online (Sandbox Code Playgroud)


akr*_*run 5

一个紧凑的选项将使用data.table.将'data.frame'转换为'data.table'(setDT(test)),按'A'分组,我们将assign(:=)转换.GRP为新的'id'列.的.GRP将是值的在"A"的每个唯一值的序列.

library(data.table)
setDT(test)[, id:=.GRP, A]
Run Code Online (Sandbox Code Playgroud)

如果'A'的值发生变化3, 3, 4, 3,我们想要1, 1, 2, 3'id'

setDT(test)[, id:= rleid(A)]
Run Code Online (Sandbox Code Playgroud)

或者我们将'A'转换为factor类,然后将其强制转换为numeric/integer

library(dplyr)
test %>%
    mutate(id = as.integer(factor(A)))
Run Code Online (Sandbox Code Playgroud)

或者我们可以使用match'A'中的unique值'A'.

test %>%
     mutate(id = match(A, unique(A)))
Run Code Online (Sandbox Code Playgroud)

或者从dplyr版本> 0.4.0,我们可以使用group_indices(它在dupe链接中)

test %>%
      mutate(id=group_indices_(test, .dots= "A"))
Run Code Online (Sandbox Code Playgroud)