首页 > 解决方案 > 像 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)

这一定是一个重复的问题,但我找不到正确的问题。

标签: r

解决方案


如何将NAs 替换为 0 ,然后cumsum转换为factorinteger

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,它将失败。


推荐阅读