r - 像 rleid 但忽略 NA
问题描述
我有一个包含数值和 NA 的向量。我想要另一个相同长度的向量,由每次在原始数字中出现新数字时计数的 Id 组成。
#What I have
have<-c(1.1, NA, 1.1, NA, NA, 1.1, NA,
1.5, NA, 2, NA, 1.5,
NA, 1.1, NA, NA, 1.5, NA)
#What I want
want<-c(1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7, 8, 8)
#Both what I have and want side by side
cbind(want,have)
我试过的
#This is pretty far off, it both treats NA's as not duplicated and treats
cbind(have,cumsum(!duplicated(have)))
#This is almost there, but NAs get counted as new groups
cbind(have,rleid(have))
#Can't fill down because some are duplicated between NA's
cbind(rleid(fill(as.data.frame(have),have)$have),have)
这一定是一个重复的问题,但我找不到正确的问题。
解决方案
如何将NA
s 替换为 0 ,然后cumsum
转换为factor
integer
as.integer(factor(cumsum(replace(have, is.na(have), 0))))
#[1] 1 1 2 2 2 3 3 4 4 5 5 6 6 7 7 7 8 8
虽然它适用于此处给出的数据,但这不是完整的证明方法,如果您的数据中有实际的 0,它将失败。
推荐阅读
- python-3.x - 在 Pandas 中使用正则表达式进行数据清理
- amazon-web-services - 围绕在 AWS IAM 中创建角色的元权限?
- javascript - 使用重力/碰撞检测/效果将气泡图升级到 v4+
- mysql - Ubuntu 20 无法卸载 mysql 服务器
- flutter - 如何在 Dart 中创建一个简单的 Tuple 类?
- c# - 使用 Entity Framework Core 5,如何嵌套查询并且仍然有 IQueryable?
- swift - iCloud - 将 CKQuery 结果发送到 TableView
- python - 从应用程序收到的烧瓶不完整响应
- python - Python中带有for循环的Zip方法
- python - 在 pythran 中写入文本文件失败