首页 > 解决方案 > 根据指标添加反向索引

问题描述

我有一个像这样的向量

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]))
}

标签: rvector

解决方案


我们可以使用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

更新

为了保持最后 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

推荐阅读