group - Create sequence based on grouping variable in R -
this question has answer here:
i'm looking way create sequence of numbers ($c) ascend every time string changes in($a). contingent on 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
or dplyr
df %>% group_by(b) %>% mutate(c = match(a, unique(a))) # source: local data frame [9 x 3] # groups: b # # 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
with base r
df$c <- with(df, ave(as.character(a), b, fun=function(x) match(x, unique(x))))
Comments
Post a Comment