r - 根据指标添加反向索引
问题描述
我有一个像这样的向量
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
推荐阅读
- python - 在 abstractuser django 自定义用户模型中更改密码表单或链接
- javascript - 为嵌入式 Google 地图 iframe 创建内容安全策略
- tensorflow - GradCAM(类激活图)-tape.gradient() 为微调模型返回 None
- c# - 如何将 .NET 桌面应用程序复制到另一台计算机?
- python - 使用 NDCG 评估推荐系统时,相关性分数和预测分数是什么?
- javascript - 如何在 chrome 扩展中使用 aes-js 库?
- stochastic - 两个 Galton-Watson 过程之间的关系
- mysql - MySql:如何在子查询中跳过连接
- apache-camel - 无法自动创建组件:restlet
- php - vlucas/valitron PHP 验证器。如何使用规则数组添加自定义消息?