1

Does anyone know how to remove continuously repeating values? Not just repeating values with unique() function.

So for example, I want:

0,0,0,0,1,1,1,2,2,2,3,3,3,3,2,2,1,2 

to become

0,1,2,3,2,1,2

and not just

0,1,2,3

Is there a word to describe this? I'm sure that the solution is out there somewhere and I just can't find it because I don't know the word for it.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Robo
  • 25
  • 6

2 Answers2

2

Keep a value when it's difference from the previous value is not zero (and keep the first one):

x <- c(0,0,0,0,1,1,1,2,2,2,3,3,3,3,2,2,1,2)
x[c(1, diff(x)) != 0]

# [1] 0 1 2 3 2 1 2
Ape
  • 1,159
  • 6
  • 11
  • Thank you! It works perfectly. So I guess the term is consecutive. Can't believe I forgot about it. I'll delete this post soon. Sorry for the duplicate :( – Robo Jun 22 '18 at 09:28
  • 2
    @Robo You shouldn't delete: https://meta.stackoverflow.com/questions/265736/should-i-delete-my-question-if-it-is-marked-as-a-duplicate – s_baldur Jun 22 '18 at 09:37
  • THis solution fails if vector is not numeric – s_baldur Jun 22 '18 at 09:39
0
v <- c(0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 2, 2, 1, 2)
rle(v)$values

Output:

[1] 0 1 2 3 2 1 2
mpalanco
  • 12,960
  • 2
  • 59
  • 67
  • This one also work perfectly! Thank you – Robo Jun 22 '18 at 09:32
  • This question had already beeen marked as a duplicate of another one which has as an accepted solution this precise method. – s_baldur Jun 22 '18 at 09:36
  • 2
    @snoram Most likely mpalanco didn't see it marked as duplicated when posting the answer. – zx8754 Jun 22 '18 at 09:41
  • @snoram yes, sorry, no need to downvote, as zx8754 said, I did not see it marked as duplicate. AFAIK if it is marked as a duplicate I wouldn't have been able to post an answer. Should I delete my answer? – mpalanco Jun 22 '18 at 10:15
  • My mistake. Sorry. It showed it was marked as duplicate 3 minutes earlier... but I understand that is not a lot of time. – s_baldur Jun 22 '18 at 12:46