为R中的数字列表分配顺序

Assign order to list of numbers in R

假设我有这样一个向量

lst <- c(2,3,4,6,7,9,10)

是否可以按顺序对项目进行编号?

预期输出

lst.rank <- c(1,2,3,1,2,1,2)
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
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

本着与 d.b 的回答相同的精神,但使用 rlesequence

sequence(rle(cumsum(c(1, diff(lst)) != 1))$lengths)
[1] 1 2 3 1 2 1 2