根据指标添加反向索引

时间:2018-08-31 06:35:33

标签: r vector

我有一个像这样的载体

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

我现在想生成第二个向量,该向量向后计数直至达到1,然后重新开始。

结果将是

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 个答案:

答案 0 :(得分:4)

我们可以使用avecumsum创建组,并计算每个组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

更新

要使所有内容都保留在最后1个之后,我们可以做到

#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
相关问题