I\'ve been googling quite unsuccessfully how to increment conditionally in tidyverse. What I want to do is check if value in a column is greater than some x
, and if
This can be done using a cumulative sum, which increments each time the value is greater than 100, for example:
df_x %>%
group_by(id) %>%
mutate(increment = 1 + cumsum(time > 100))
# A tibble: 9 x 3
# Groups: id [4]
id time increment
<dbl> <dbl> <dbl>
1 1. 20. 1.
2 1. 30. 1.
3 1. 101. 2.
4 2. 33. 1.
5 3. 50. 1.
6 3. 101. 2.
7 3. 30. 2.
8 3. 110. 3.
9 4. 30. 1.
I used 1 + cumsum(...)
in order to start the first group from 1 instad of 0. Not that a group might start with a 2 if the first value is >100 in a given id-group.