Create a sequence based on the grouping variable in R
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 to share
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 to share