Reputation: 683
How to the get the index of last element of each run?
For example: Let us consider a vector
x=c(1,2,3,4,4,4,5,6,6,7,8,9,9,9,9)
Want get the output vector
x1=1 2 3 6 7 9 10 11 15
Tried using:
rank(x)
It is not giving the desired result.
Upvotes: 1
Views: 69
Reputation: 109
Using the which() function in R
k<-as.vector(unique(x))
x1<-vector()
for(i in 1:length(k)){
x1[i]=tail(which(x==k[i]),1)
}
Upvotes: 1
Reputation: 70336
(Probably a dupe, but here you go..)
You can use the magic powers of ?rle
combined with cumsum
:
cumsum(rle(x)$lengths)
#[1] 1 2 3 6 7 9 10 11 15
The output of rle
is:
rle(x)
#Run Length Encoding
# lengths: int [1:9] 1 1 1 3 1 2 1 1 4
# values : num [1:9] 1 2 3 4 5 6 7 8 9
Upvotes: 5