Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if there are x consecutive duplicates in a vector in R

Tags:

r

I have the following vector:

p<-c(0,0,1,1,1,3,2,3,2,2,2,2)

I'm trying to write a function that returns TRUE if there are x consecutive duplicates in the vector.

The function call found_duplications(p,3) will return True because there are three consecutive 1's. The function call found_duplications(p,5) will return False because there are no 5 consecutive duplicates of a number. The function call found_duplications(p,4) will return True because there are four consecutive 4's.

I have a couple ideas. There's the duplicated() function:

duplicated(p)
> [1] FALSE  TRUE FALSE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE

I can make a for loop that counts the number of TRUE's in the vector but the problem is that the consecutive counter would be off by one. Can you guys think of any other solutions?

like image 855
cooldood3490 Avatar asked Dec 11 '22 00:12

cooldood3490


2 Answers

You could also do

find.dup <- function(x, n){
 n %in% rle(x)$lengths
}

find.dup(p,3)
#[1] TRUE
find.dup(p,2)
#[1] TRUE
find.dup(p,5)
#[1] FALSE
find.dup(p,4)
#[1] TRUE
like image 58
akrun Avatar answered Apr 30 '23 23:04

akrun


p<-c(0,0,1,1,1,3,2,3,2,2,2,2)

find.dup <- function(x, n) {
  consec <- 1
  for(i in 2:length(x)) {
    if(x[i] == x[i-1]) {
      consec <- consec + 1
    } else {
      consec <- 1
    }
    if(consec == n)
      return(TRUE) # or you could return x[i]
  }
  return(FALSE)
}

find.dup(p,3)
# [1] TRUE

find.dup(p,4)
# [1] TRUE

find.dup(p,5)
# [1] FALSE
like image 38
Dominic Comtois Avatar answered May 01 '23 00:05

Dominic Comtois