J L
J L

Reputation: 13

Creating a variable that counts the number of another variable satisfying a condition in R

id date score Repeat
1 1990 1 1
1 1991 3 2
1 1992 1.5 3
1 1993 -1 0
2 1989 1 1
2 1990 0 0
2 1991 1 1
2 1992 2 2
3 1993 -3 0
3 1994 -2 0
3 1995 3 1
3 1996 4 2

Like the above table, I have ID, date and two other variables, score and repeat. If score is greater than 0 for consecutive dates for the same person, it adds 1 to repeat. If not it suddenly becomes 0. I want to write a code to make this work for repeat variable. Thanks in advance!

Upvotes: 0

Views: 31

Answers (1)

dcsuka
dcsuka

Reputation: 2997

Simple solution using hutilscpp. Let me know if this works:

library(dplyr)
library(hutilscpp)
df %>%
  group_by(id) %>%
  mutate(repeats = hutilscpp::cumsum_reset(score > 0))

Upvotes: 0

Related Questions