Reputation: 4790
Suppose I have a vector like this
lst <- c(2,3,4,6,7,9,10)
Is it possible to number the items in sequence?
Expected Output
lst.rank <- c(1,2,3,1,2,1,2)
Upvotes: 2
Views: 241
Reputation: 38510
In the same spirit as d.b's answer, but using rle
and sequence
.
sequence(rle(cumsum(c(1, diff(lst)) != 1))$lengths)
[1] 1 2 3 1 2 1 2
Upvotes: 2
Reputation: 402
lst <- c(2,3,4,6,7,9,10)
m = 1
for (i in 1:(length(lst)-1) ){
if (lst[i+1] == lst[i]+1){
lst[i]=m
if(i == length(lst)-1) lst[i+1] = m + 1
m = m+1
}
else{
lst[i]=m
m = 1
}
}
lst
Upvotes: 0
Reputation: 32548
unlist(lapply(split(lst, cumsum(c(1, diff(lst)) != 1)), seq_along), use.names = FALSE)
#OR
ave(cumsum(c(1, diff(lst)) != 1), cumsum(c(1, diff(lst)) != 1), FUN = seq_along)
#[1] 1 2 3 1 2 1 2
Upvotes: 2