Create a sequence based on the grouping variable in R

I'm looking for a way to create a sequence of numbers ($ C) that are raised every time the string changes ($ A). It depends on the grouping variable ($ B). Example:

A    B C
a1   1 1
a1   1 1
a1   1 1
a10  1 2
a10  1 2
a2   1 3
a1   2 1
a20  2 2
a30  2 3

      

+3


source to share


2 answers


Or using dplyr

df %>% group_by(B) %>% mutate(C = match(A, unique(A)))
# Source: local data frame [9 x 3]
# Groups: B
# 
#     A B C
# 1  a1 1 1
# 2  a1 1 1
# 3  a1 1 1
# 4 a10 1 2
# 5 a10 1 2
# 6  a2 1 3
# 7  a1 2 1
# 8 a20 2 2
# 9 a30 2 3

      



FROM base R

df$C <- with(df, ave(as.character(A), B, FUN=function(x) match(x, unique(x))))

      

+1


source


Using devel version data.table

new function can be usedrleid



library(data.table) # v >= 1.9.5
setDT(df)[, C := rleid(A), by = B]
#      A B C
# 1:  a1 1 1
# 2:  a1 1 1
# 3:  a1 1 1
# 4: a10 1 2
# 5: a10 1 2
# 6:  a2 1 3
# 7:  a1 2 1
# 8: a20 2 2
# 9: a30 2 3

      

+4


source







All Articles