Reputation: 387
From a vector:
v <- c(2,2,2,2,5,7,7,5,5,7,3,3,3)
and according to the condition v[i] != v[i+1]
, how can I obtain:
[1] 2 5 7 5 7 3
Upvotes: 1
Views: 105
Reputation: 887991
This can be also done using diff
v[c(TRUE,diff(v)!=0)]
#[1] 2 5 7 5 7 3
Or using rleid
from library(data.table)
library(data.table)
setDT(list(v))[,V1[1L] ,rleid(V1)]$V1
#[1] 2 5 7 5 7 3
Upvotes: 1
Reputation: 6776
The rle
function will do this. rle stands for run length encoding.
v <- c(2,2,2,2,5,7,7,5,5,7,3,3,3)
rle(v)$values
## [1] 2 5 7 5 7 3
Upvotes: 4