If in a vector there are less than "n" consecutive "TRUE-s" then mutate "TRUE" to "FALSE"?

example:

vector <- round(rnorm(100, mean = 0.5, sd = 0.2), 0)
n <- 3

if there are less than 3 consecutive 1-s, those 1-s = 0.
equal or more than 3 consecutive 1-s remain intact.

vector <- round(rnorm(100, mean = 0.5, sd = 0.2), 0)
n <- 3

library(tidyverse)
(exdf <- enframe(vector))

# https://gist.github.com/brshallo/cadaa40cef6387e28924b6c3756627c9

lag_multiple <- function(x, n_vec){
  map(n_vec, ~lag(x=x,n=.,default=0)) %>% 
    set_names(paste0("lag", n_vec)) %>% 
    as_tibble()
}

(exdf2 <- mutate(exdf,
                lag_multiple(value,seq_len(n)-1)))
(exdf3 <- mutate(rowwise(exdf2),
                 s=sum(c_across(starts_with("lag")))) %>% ungroup())
(exdf4 <- mutate(exdf3,
                 value_2 = ifelse(s==n,1,0)) %>% select(starts_with("value")))

print(exdf4,n=100)
1 Like

Thank you very much, sir! Meantime I came up with an alternative solution in base R. Meant for only if n = 3.

vector <- round(rnorm(100, mean = 0.5, sd = 0.2), 0)

res <- c()

for (i in 2:(length(vector)-1)){
  
  if ((sum(vector[(i-1):(i+1)]) == 3)){
    res[i] <- TRUE 
  } else {res[i] <- FALSE}
}

res2 <- vector(mode = "numeric", length = length(res))

for (i in 2:(length(res)-1)){
  
  if (res[i] == TRUE){
    res2[(i-1):(i+1)] <- 1
  }
}

res2


This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.