Search code examples
rdplyrdatatablecounterdata-cleaning

Create a counter that only counts a certain logical value and gives the same number to repetitions


Say I have a logical value like this

rex <- c(TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, NA)

How do I create a counter which will only count for the TRUE and will group consecutive repetitions as the same value in the counter. ex. to have something like this:

1, NA, 2,2,NA, 3, NA

Solution

  • The accepted solution doesn't work for the following case:

    rex <- c(TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, NA, NA, TRUE)
    

    It prints 1 NA 2 2 NA 3 NA NA NA.

    The following function returns the correct answer:

    solution <- function (rex) {
      result <- c()
      counter <- 1
      consecutive <- FALSE
      for (i in 1:length(rex)) {
        if (rex[i] == TRUE && !is.na(rex[i]) && consecutive) {
          result <- c(result, counter)
          consecutive <- TRUE
        } else if (rex[i] == TRUE && !is.na(rex[i]) && !consecutive) {
          result <- c(result, counter)
          consecutive <- TRUE
        } else{
          if(i < length(rex) && rex[i+1] == TRUE && !is.na(rex[i+1])){
            counter <- counter + 1
          }
          result <- c(result, NA)
          consecutive <- FALSE
        }
      }
      return(result)
    }
    

    Calling solution(rex) prints 1 NA 2 2 NA 3 NA NA 4, which is the correct answer.