Search code examples
rdplyrfill

Fill down constant value, add 1 when condition is met in dplyr


I have a dataframe as follows:

step   state   
1      active
2      active
       break
1      active
2      error
3      active
       break
1      active

I want to create a new column where I fill down a constant value of 1, then add 1 to the constant fill every time a "break" row is reached, which would make the dataframe look like.

step   state     n
1      active    1
2      active    1
       break     2
1      active    2
2      error     2
3      active    2
       break     3
1      active    3

Any solution using dplyr or base r would be helpful. Thanks


Solution

  • We can use cumsum with %in% and mutate.

    library(dplyr)
    
    dat2 <- dat %>%
      mutate(n = cumsum(state %in% "break") + 1)
    dat2
    #   step  state n
    # 1    1 active 1
    # 2    2 active 1
    # 3    2  break 2
    # 4    1 active 2
    # 5    2  error 2
    # 6    3 active 2
    # 7    3  break 3
    # 8    1 active 3
    

    Data

    dat <- read.table(text = "step   state   
    1      active
    2      active
    2       break
    1      active
    2      error
    3      active
    3       break
    1      active",
                      header = TRUE)