Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Counting number of rows between rows

I have a data frame with four columns: user_id, event, and time

User_id a user_id, event is either "A" or "B", and time is time. I need to count the number of "B" values that occur before each "A" value. So if there are 3 "B" values that occur before the first "A" then that instance of "A" will get a new column with a value of 3. If there are 25 instances of "B" before the next values of "A" then that will get a value of 25. I consider myself a solid R/dplyr journeyman but this has me stumped! Thanks.

user_id   event   date_time    desired_column
1         B       2018-01-01   NA
1         B       2018-01-02   NA
1         B       2018-01-03   NA
1         B       2018-01-04   NA
1         B       2018-01-05   NA
1         A       2018-01-06   5
1         B       2018-01-07   NA
1         A       2018-01-08   1
2         B       2018-01-05   NA
2         B       2018-01-06   NA
2         A       2018-01-07   2
2         B       ...          NA
2         A       ...          1
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Using @r2Evans' data :

x$y    <- NA
which_ <- which(x$event=="A")
x$y[which_] <- diff(c(0,which_))-1

#    user_id event  date_time desired_column  y
# 1        1     B 2018-01-01             NA NA
# 2        1     B 2018-01-02             NA NA
# 3        1     B 2018-01-03             NA NA
# 4        1     B 2018-01-04             NA NA
# 5        1     B 2018-01-05             NA NA
# 6        1     A 2018-01-06              5  5
# 7        1     B 2018-01-07             NA NA
# 8        1     A 2018-01-08              1  1
# 9        2     B 2018-01-05             NA NA
# 10       2     B 2018-01-06             NA NA
# 11       2     A 2018-01-07              2  2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...