r - 根据指标添加反向指数

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

最佳答案

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

相关文章:

使用 RMarkdown 将带有颜色和 unicode 字符的 kableExtra 表渲染为 PDF

c++ - 排序函数如何作用于一对整数对的 vector ?

C++使用算法过滤类 vector

java - 如何使用paintComponent(Graphics g)绘制存储在 vector 中的对象

python - 将元素(向量)添加到 rpy2 中的列表

r - 根据其他列中的值条件跨数据框中的列应用 if else 语句

r - 如何删除R中的所有行直到某个值

sql-server - 如何使用 R 和 dplyr 连接不同 SQL 数据库中的表?

r - 更改值顺序时样本的 Set.seed 问题

c++ - 二维 vector 中的运算符 []