jaclea
jaclea

Reputation: 125

Remove duplicates in vector to next value

I have a vector consisting of integers which can take a finite number of values. Consider the case where the values is 0,1,2.

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

I want to delete replicates of values until the next differnet value. After doing this the result show be

0 1 0 2

Hence I want to do something like unique (which would have given 0,1,2) but i want to take the ordering into account.

Thanks

Upvotes: 1

Views: 129

Answers (2)

Carl Witthoft
Carl Witthoft

Reputation: 21492

Use my favorite tool:

Rgames> rle(a<-c(0,0,0,1,1,0,0,2,2,2))
Run Length Encoding
  lengths: int [1:4] 3 2 2 3
  values : num [1:4] 0 1 0 2

Upvotes: 2

Oleg Sklyar
Oleg Sklyar

Reputation: 10082

try (assuming no NAs):

a[c(1, diff(a)) != 0]

Upvotes: 2

Related Questions