Home > Mobile >  Count number of rows containing text between two rows containing other text and stopping
Count number of rows containing text between two rows containing other text and stopping

Time:10-21

I have a data frame column like this :
enter image description here

My goal is to have a counter that will calculates the number of "At Sea" between each non-at-sea. like this: enter image description here

I am trying using a counter type loop :

at_sea <- my_file %>% pull(`My_column`)
counter <- 0

    for(days in at_sea){
      if(days == "At Sea"){
        counter <- counter   1
      }else if(days != "At Sea"){
        break
      }
      counter 
    }

Since i have a break to stop the counter when it encounter a non-at-sea, it always returns zero if the first row is not-at-sea. How can I fix so that i can have all iterations of that column?

CodePudding user response:

at_sea = c("in transit", "full turn", "at sea", "in transit", 
           "in transit", "in transit", "at sea", "at sea", "full turn")

groups <- with(rle(at_sea), rep(lengths, lengths))

count <- c(0, ifelse(head(at_sea, -1) == "at sea" & tail(at_sea,-1) != "at sea", head(groups, -1), 0))

count
#> [1] 0 0 0 1 0 0 0 0 2
  • Related