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
Adjacent identical elements in vector in R
Question
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.
Solution
OTHER TIPS
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow