Conditional increment tidyverse

后端 未结 1 1350
天涯浪人
天涯浪人 2021-01-22 15:36

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

相关标签:
1条回答
  • 2021-01-22 15:58

    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.

    0 讨论(0)
提交回复
热议问题