Pierre
Pierre

Reputation: 387

First occurrence of each value in a vector depending on a condition

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

Answers (2)

akrun
akrun

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

tblznbits
tblznbits

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

Related Questions