Given the vector
vec <- c(1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0)
the number of switches can simply be calculated with
cumsum(diff(vec) == 1)
However given the df
group <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
df_test <- data.frame(vec,group)
and using
df_test <- df_test %>%
group_by(group) %>%
mutate(n_switches = cumsum(diff(vec) == 1))%>%
ungroup()
the calculation fails because n_switches has 2 rows (1 per group) less than vec.
How can I overcome this problem and generate n_switches per group? Any help would be much appreciated!