let's say one has the following simplified data frame, composed by the variable 'Date' only, that contains a set of dates:
Date |
---|
2022-01-01 |
2022-01-01 |
2022-01-02 |
2022-01-04 |
2022-01-04 |
2022-01-06 |
I need to compute an ID counter variable that assumes values equal to 1 for the first record only and a cumulative value for the remaining ones. Specifically, if 2 dates are consecutive then the ID counter remains equal to the previous one, otherwise it increases by 1.
By assuming that, R has to return the following table as output:
Date | ID.Counter |
---|---|
2022-01-01 | 1 |
2022-01-01 | 1 |
2022-01-02 | 1 |
2022-01-04 | 2 |
2022-01-04 | 2 |
2022-01-06 | 3 |
Could someone help me?
I tried to solve this simple problem by running:
library(dplyr)
what_i_have <- c('2022-12-31','2022-12-31','2022-12-31','2022-01-01','2022-01-01','2022-01-02','2022-01-03','2022-01-03')
what_i_have <- as.data.frame(what_i_have)
what_i_have <- what_i_have %>%
mutate(ID = 1,
ID = if_else(Date == lag(Date) ,ID = lag(ID),ID+1))
but R returns an error in the mutate() statement; specifically, the error is:
Error in
mutate()
: In argument:ID = if_else(Date == lag(Date), ID = lag(ID), ID + 1)
. Caused by error inif_else()
: must be empty. Problematic argument: ID = lag(ID) Runrlang::last_trace()
to see where the error occurred.