Incremental identifiers in data frame R

I have the following data frame:

> 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

Now I want each line to have an identifier that only increases when the value of A. changes. This is what I 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
+4
source share
2 answers
library(dplyr)

test %>% mutate(id = dense_rank(A))
+6
source

One compact option will use data.table. Convert 'data.frame' to 'data.table' ( setDT(test)), grouped by 'A', we assign ( :=) .GRPas the new column “id”. .GRPwill be a sequence of values ​​for each unique value in 'A'.

library(data.table)
setDT(test)[, id:=.GRP, A]

, "A" 3, 3, 4, 3, 1, 1, 2, 3 'id'

setDT(test)[, id:= rleid(A)]

'A' factor, numeric/integer

library(dplyr)
test %>%
    mutate(id = as.integer(factor(A)))

match 'A' unique 'A'.

test %>%
     mutate(id = match(A, unique(A)))

dplyr version > 0.4.0, group_indices ( dupe)

test %>%
      mutate(id=group_indices_(test, .dots= "A"))
+5

Source: https://habr.com/ru/post/1628558/


All Articles