首页 > 解决方案 > 如何创建一个计数器,将重复分组为相同的值,同时忽略 NA

问题描述

我的数据框有超过 5000 行的模拟。我的问题是这样的

rex <- c("Positive", "Negative", NA, "Positive", "Negative", "Negative")

我想创建一个返回的计数器:

1,2,NA,3,4,4

结果,在重复相同值的情况下,具有相同的计数器。

感谢任何帮助。谢谢,

最好的

标签: r

解决方案


在这里我们可以使用data.table::rleid例如

library(data.table)
rex <- c("Positive", "Negative", NA, "Positive", "Negative", "Negative",NA,"Negative")
idx <- !is.na(rex)

如果rex <- c("Positive", NA, "Positive")应该输出 1, NA, 1

as.numeric(replace(rex, idx, rleid(rex[idx])))
[1]  1  2 NA  3  4  4 NA  4

如果rex <- c("Positive", NA, "Positive")应该输出 1, NA, 2

as.numeric(replace(rex, idx, rleid(rleid(rex)[idx])))
[1]  1  2 NA  3  4  4 NA  5

推荐阅读