Set unique IDs which start from zero in R data.frame

Viewed 119

I have a data frame that looks like this

column1
 1
 1
 2
 3
 3

and I would like to give a unique ID to each element. My problem is that I can not find a way the unique IDs to start from zero and be like this

column1 column2
 1        0
 1        0
 2        1
 3        2
 3        2

Any help is appreciated

2 Answers

Try this, cur_group_id from dplyr will create the id from 1 but you can easily make it to start from zero:

library(dplyr)
#Data
df <- structure(list(column1 = c(0L, 1L, 2L, 3L, 3L)), class = "data.frame", row.names = c(NA,-5L))
#Mutate
df %>% group_by(column1) %>% mutate(id=cur_group_id()-1)

# A tibble: 5 x 2
# Groups:   column1 [4]
  column1    id
    <int> <dbl>
1       0     0
2       1     1
3       2     2
4       3     3
5       3     3

We could use match

library(dplyr)
df1 %>% 
     mutate(column2 = match(column1, unique(column1)) - 1)

data

df1 <- structure(list(column1 = c(1L, 1L, 2L, 3L, 3L)), class = "data.frame",
row.names = c(NA, 
-5L))
Related