cooldood3490
cooldood3490

Reputation: 2488

Determine if there are x consecutive duplicates in a vector in 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?

Upvotes: 4

Views: 2224

Answers (2)

akrun
akrun

Reputation: 886948

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

Upvotes: 10

Dominic Comtois
Dominic Comtois

Reputation: 10401

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

Upvotes: 2

Related Questions