我有一个这样的向量
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]))
}
最佳答案
我们可以使用 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
关于r - 根据指标添加反向指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52109763/