Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect successive repetitions in R

Tags:

r

in R, I would like to find out whether there are successive repetitions in my data.

A <- c(1,2,3,3,4)

B <- c(1,2,3,4,3)

For A, I want to get TRUE, since there are two 3s directly one after the other.

For B, I want to get FALSE because the 3s are separated by the 4.

Thanks community! pointingeye

like image 207
pointingeye Avatar asked Feb 20 '15 15:02

pointingeye


2 Answers

You can use rle for this:

> rle(A)
Run Length Encoding
  lengths: int [1:4] 1 1 2 1
  values : num [1:4] 1 2 3 4
> any(rle(A)$lengths > 1)
[1] TRUE
> any(rle(B)$lengths > 1)
[1] FALSE
like image 193
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 30 '22 17:10

A5C1D2H2I1M1N2O1R2T1


Try rle:

any(rle(A)$lengths > 1)
#[1] TRUE
any(rle(B)$lengths > 1)
#[1] FALSE

Alternative solution (diff):

any(diff(A)==0)
#[1] TRUE
any(diff(B)==0)
#[1] FALSE
like image 43
Colonel Beauvel Avatar answered Oct 30 '22 17:10

Colonel Beauvel