Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Remove repeated values and keep the first one in a binary vector

I would like to remove the repeated ones but keep the first in a binary vector:

x = c(0,0,1,1,0,1,0,1,1,1,0,1) # the input 
y = c(0,0,1,0,1,0,1,0,1)     # the desired output

i.e., one 1 and two 1's of the first and third set of 1's are removed, respectively, and the first in the set is kept.

I am trying to use rle with cumsum but have not yet figured it out. Any suggestion would be appreciated.

like image 685
Francis Avatar asked Dec 14 '15 16:12

Francis


4 Answers

Using rle/inverse.rle

res <- rle(x)
res$lengths[res$values == 1] <- 1
inverse.rle(res)
## [1] 0 0 1 0 1 0 1 0 1
like image 97
David Arenburg Avatar answered Oct 23 '22 13:10

David Arenburg


We can use diff:

x[c(1, diff(x)) == 1 | x == 0]
like image 30
jeremycg Avatar answered Oct 23 '22 13:10

jeremycg


x = c(0,0,1,1,0,1,0,1,1,1,0,1)
x[!(x == 1 & #remove each value that is a 1
    c(x[-1] == 1, FALSE) #followed by a 1 (never the case for the last value)
  )]
#[1] 0 0 1 0 1 0 1 0 1
like image 32
Roland Avatar answered Oct 23 '22 13:10

Roland


x = c(0,0,1,1,0,1,0,1,1,1,0,1)
x1 <- rle(x)
x1$lengths[x1$values==1] <- 1
inverse.rle(x1)
like image 23
Ven Yao Avatar answered Oct 23 '22 14:10

Ven Yao