Count rows with specific start and stop

Hi!
I have a dataframe like this

Regnr DateTime Start Stopp
XXX 16-09-2020 02:00 NA NA
XXX 16-09-2020 02:10 1 NA
XXX 16-09-2020 02:20 NA NA
XXX 16-09-2020 02:30 NA NA
XXX 16-09-2020 02:40 NA NA
XXX 16-09-2020 02:50 NA 1
XXX 16-09-2020 03:00 NA NA
XXX 16-09-2020 03:10 NA NA
XXX 16-09-2020 03:20 1 NA
XXX 16-09-2020 03:30 NA NA

I want a new column with counts, startting where Start=1, and ending where stop=1. Then next count when Start=1 again, etc. Could anyone help with this?

Regards Marit

(somedata <- data.frame(
      start = c(NA, 1L, NA, NA, NA, NA, NA, NA, 1L, NA),
        stop = c(NA, NA, NA, NA, NA, 1L, NA, NA, NA, NA)
))

library(tidyverse)
(result_1 <- mutate(somedata ,
       startx = cumsum(ifelse(is.na(start),0L,1L))) |> 
  group_by(startx) |> mutate(
       rn=row_number()))
1 Like