Identify and replace duplicate elements from a vector

I have a vector that is under

a<- c(1,1,1,2,3,2,2,2,2,1,0,0,0,0,2,3,4,4,1,1) 

Here we see that there are many repeating elements, i.e. they are repeated. I want code that can replace all elements that are sequential and are duplicated by 0, except for the first element. The result I need is

 a<- c(1,0,0,2,3,2,0,0,0,1,0,0,0,0,2,3,4,0,1,0) 

I tried

 unique(a) #which gives [1] 1 2 3 0 4 
+4
source share
2 answers

You can create a lagging series and compare

 > a [1] 1 1 1 2 3 2 2 2 2 1 0 0 0 0 2 3 4 4 1 1 > ifelse(a == c(a[1]-1,a[(1:length(a)-1)]) , 0 , a) [1] 1 0 0 2 3 2 0 0 0 1 0 0 0 0 2 3 4 0 1 0 
+4
source
 replace(a, duplicated(c(0, cumsum(abs(diff(a))))), 0) # [1] 1 0 0 2 3 2 0 0 0 1 0 0 0 0 2 3 4 0 1 0 
+4
source

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


All Articles