Lets say I have a data frame with an ID and a variable in which the response is either ON or OFF. I want to count the number of runs of "ON" per group. I had nearly managed this but realised my solution wasn't working on the first or last value in the group depending on whether I was trying to use lead or lag.
I have searched SO and can find similar problems but non seem to match this exactly.
id <- c("a", "a", "a", "a", "a", "b", "b", "b", "b", "b","c", "c","c","c","c","c","c","c" )
category <- c("ON", "OFF", "OFF", "ON", "ON", "ON", "OFF", "OFF", "ON", "ON", "OFF", "OFF","OFF","OFF","OFF", "ON", "ON","ON")
dat<-data.frame(id, category)
My attempt so far which is not working I think because it doesn't work if the run starts as "ON" in a group
summary(dat %>% group_by(id)%>% filter(category == "ON", lead(category!="ON"))%>% count(category) %>% arrange(n))
Very grateful for any assistance. My actual dataset is 40,000 rows with 120 id's and in each id the category may start as either ON or OFF
Output would be something like this:
# id category n
# a:1 OFF:0 Min. :1
# b:1 ON :2 1st Qu.:1
# c:0 Median :1
# Mean :1
# 3rd Qu.:1
# Max. :1
So that the interpretation would be 2 id's has a run of "ON" at any point and the median number of runs of ON (in this tiny sample) was 1