Detect consecutive repetitions in R

in R, I would like to know if there are consecutive 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 another.

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

Thanks to the community! pointingeye

+6
source share
3 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 
+6
source

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 
+4
source
 0 %in% diff(A) - TRUE 0 %in% diff(B) - FALSE 

Only in the case of (at least) two consecutive identical differences of numbers can be equal to 0.

+2
source

Source: https://habr.com/ru/post/982793/


All Articles