代码之家  ›  专栏  ›  技术社区  ›  spore234

根据指标添加反向指数

  •  3
  • spore234  · 技术社区  · 6 年前

    我有一个这样的向量

    v <- c(0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,1,0)
    

    结果是

    r <- c(6,5,4,3,2,1,8,7,6,5,4,3,2,1,4,3,2,1,0)
    

    我试过这样的方法,但没有成功:

    lv <- c(1, which(v == 1))
    
    res <- c()
    for(i in 1:(length(lv)-1)) {
      res <- c(res, rev(lv[i]:lv[i+1]))
    }
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Ronak Shah    6 年前

    我们可以用 ave 使用创建组 cumsum 数一数顺序 reverse 在每组。然后,我们将1重新分配给它们在中的原始位置 new_seq .

    new_seq <- ave(v, cumsum(v==1), FUN = function(x) rev(seq_along(x))) + 1
    new_seq[v == 1] <- 1
    
    new_seq
    #[1] 6 5 4 3 2 1 8 7 6 5 4 3 2 1 4 3 2 1 2
    

    更新

    #Make groups
    indx <- cumsum(v==1)
    
    #Create reverse sequential counting in each group
    new_seq <- ave(v, indx, FUN = function(x) rev(seq_along(x))) + 1
    
    #Keep everything after last 1 as it is
    new_seq[which.max(indx) : length(v)] <- v[which.max(indx) : length(v)]
    
    #Change 1's same as their original position
    new_seq[v == 1] <- 1
    
    new_seq
    #[1] 6 5 4 3 2 1 8 7 6 5 4 3 2 1 4 3 2 1 0