将顺序分配给R中的数字列表

时间:2017-11-07 16:21:46

标签: r sequences

假设我有这样的矢量

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

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

预期产出

lst.rank <- c(1,2,3,1,2,1,2)

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

与d.b的答案一样,但使用rlesequence

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

答案 2 :(得分:0)

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