I have a dataframe measuring logins per month. I'm trying to create a counter measuring months_since_zero_login that only adds when the logins in a month is zero. For the first month, each customer's counter will start from zero.
Here is the data:
library(tidyverse)
obs <- seq(as.Date('2020-01-01'),
as.Date('2020-05-01'),
by = "month")
table <- tibble(customer = seq(1:3))
#output
table <- table %>%
crossing(obs) %>%
mutate(login = c(3, 0, 0, 0, 2,
0, 1, 5, 0, 0,
1, 3, 1, 5, 0))
This is the expected result:
customer obs login months_since_zero_login
<int> <date> <dbl> <dbl>
1 1 2020-01-01 3 0
2 1 2020-02-01 0 0
3 1 2020-03-01 0 1
4 1 2020-04-01 0 2
5 1 2020-05-01 2 0
6 2 2020-01-01 0 0
7 2 2020-02-01 1 0
8 2 2020-03-01 5 0
9 2 2020-04-01 0 0
10 2 2020-05-01 0 1
11 3 2020-01-01 1 0
12 3 2020-02-01 3 0
13 3 2020-03-01 1 0
14 3 2020-04-01 5 0
15 3 2020-05-01 0 0
This is my code so far but I'm stuck on how to increase the counter by 1 when there are consecutive zeroes (in the case of customer 1)
table %>%
group_by(customer) %>%
mutate(months_since_zero_login = case_when(
row_number() == 1 ~ 0,
lag(login) == 0 & login == 0 ~ 1,
TRUE ~ 0
))
#does not increase counter when there are consecutive zeroes