Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

r - Using dplyr to get cumulative count by group

Thanks in advance. I have the following data:

df <- data.frame(person=c(1,1,1,1,2,2,2,2,3,3,3,3), 
             neighborhood=c("A","A","A","A","B","B","C","C","D","D","E","F"))

I would like to generate a new column that gives the cumulative count of neighborhoods that each person moves through as the panel progresses. Like such:

df2 <- data.frame(person=c(1,1,1,1,2,2,2,2,3,3,3,3), 
             neighborhood=c("A","A","A","A","B","B","C","C","D","D","E","F"),
             moved=c(0,0,0,0,0,0,1,1,0,0,1,2)
             )

Thanks again.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We can use group by 'person', then create the 'moved' by matching the 'neighborhood' with its unique values to get the index and subtract 1.

df %>%
   group_by(person) %>% 
   mutate(moved = match(neighborhood, unique(neighborhood))-1)
#   person neighborhood moved
#    <dbl>       <fctr> <dbl>
#1       1            A     0
#2       1            A     0
#3       1            A     0
#4       1            A     0
#5       2            B     0
#6       2            B     0
#7       2            C     1
#8       2            C     1
#9       3            D     0
#10      3            D     0
#11      3            E     1
#12      3            F     2

or use factor with levels specified as the unique values in 'neighborhood', coerce to 'integer' and subtract 1.

df %>%
   group_by(person) %>% 
   mutate(moved = as.integer(factor(neighborhood, levels = unique(neighborhood)))-1)
#   person neighborhood moved
#    <dbl>       <fctr> <dbl>
#1       1            A     0
#2       1            A     0
#3       1            A     0
#4       1            A     0
#5       2            B     0
#6       2            B     0
#7       2            C     1
#8       2            C     1
#9       3            D     0
#10      3            D     0
#11      3            E     1
#12      3            F     2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...