Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R function to identify elements same as previous element

Tags:

r

v = c(1,0,1, 1,1,2, 1,2,2, 0,0,1)

I'm looking for a function that will give me:

c(F,F,F, T,T,F, F,F,T, F,T,F)

I.e. true at element ix if v[ix] equals element v[ix-1].

By the way, duplicated(v) is not what I want, as it compares to all earlier rows, and gives me:

[1] FALSE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
like image 802
Darren Cook Avatar asked Jul 19 '26 07:07

Darren Cook


2 Answers

v[-1] == v[-length(v)]

Note that your requirement is undefined for v[1].

like image 156
Hong Ooi Avatar answered Jul 20 '26 20:07

Hong Ooi


If you have only numeric values then you could also use diff function. If 0 -> equal, else not equal

 v = c(1,0,1, 1,1,2, 1,2,2, 0,0,1)
 diff(v)
 ## [1] -1  1  0  0  1 -1  1  0 -2  0  1
 !as.logical(diff(v))
 ## [1] FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE
like image 42
bartektartanus Avatar answered Jul 20 '26 20:07

bartektartanus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!