How to assign a unique ID number to each group of identical values in a column [duplicate]

Solution 1:

How about

df2 <- transform(df,id=as.numeric(factor(sample)))

?

I think this (cribbed from Add ID column by group) should be slightly more efficient, although perhaps a little harder to remember:

df3 <- transform(df, id=match(sample, unique(sample)))
all.equal(df2,df3)  ## TRUE

If you want to do this in tidyverse:

library(dplyr)
df %>% group_by(sample) %>% mutate(id=cur_group_id())

Solution 2:

Here's a data.table solution

library(data.table)
setDT(df)[, id := .GRP, by = sample]