Reputation: 555
Is there an efficient way in R to recognize adjacent identical elements ?
Let's say I have this vector:
(Vx)
1 2 2 1 3 3 3 1 2 2 3 3 0
And I'd like to get:
0 1 1 0 1 1 1 0 1 1 1 1 0
Is there any clean way to do this ? I'm trying to avoid loops or cumbersome functions but so far I haven't had any luck.
Thanks.
Upvotes: 0
Views: 167
Reputation: 269634
Try rle
and inverse.rle
like this:
r <- rle(vx)
r$values <- (r$lengths > 1) + 0
inverse.rle(r)
giving:
[1] 0 1 1 0 1 1 1 0 1 1 1 1 0
Upvotes: 1
Reputation: 20811
vec <- c(1, 2, 2, 1, 3, 3, 3, 1, 2, 2, 3, 3, 0)
l <- rle(vec)$lengths
rep(ifelse(l == 1, 0, 1), times = l)
# [1] 0 1 1 0 1 1 1 0 1 1 1 1 0
Upvotes: 2