How can we in a
, obtain the index of the first element of the repeated value (index of first 1
, first 2
, first 3
...)?
a <- c(rep(1, 3), rep(2, 2), rep(3, 1), rep(4, 2))
desired.output <- c(1, 4, 6, 7)
How can we in a
, obtain the index of the first element of the repeated value (index of first 1
, first 2
, first 3
...)?
a <- c(rep(1, 3), rep(2, 2), rep(3, 1), rep(4, 2))
desired.output <- c(1, 4, 6, 7)
Another option is match
match(unique(a), a)
# [1] 1 4 6 7
From help('match')
match returns a vector of the positions of (first) matches of its first argument in its second.
One option is tapply
as.vector(tapply(seq_along(a), a, FUN = `[`, 1))
#[1] 1 4 6 7
Or using
which(!duplicated(a))
Or with which
and diff
which(c(TRUE, !!diff(a)))
Or when the vector is not numeric
which(c(TRUE, a[-1] != a[-length(a)]))