My input is a vector like this
v = c(1,2,2,3,4,5,4,1,1)
unique(v) == c(1,2,3,4,5)
instead, I need to check and operate uniqueness only on pairs of subsequent element:
.f(v) == c(1,2,3,4,5,4,1)
CodePudding user response:
Use rle from base R and extract the 'values'
rle(v)$values
[1] 1 2 3 4 5 4 1
unique gets the unique values from the whole dataset, whereas rle returns a list of 'values' and its lengths for each adjacent unique value
Or another option is to do a comparison with the current and adjacent value and apply duplicated to subset the vector
v[!duplicated(cumsum(c(TRUE, v[-1] != v[-length(v)])))]
[1] 1 2 3 4 5 4 1
CodePudding user response:
Another possible solution:
v[v != dplyr::lag(v, default = Inf)]
#> [1] 1 2 3 4 5 4 1
