【问题标题】:How to create a counter that groups repeats into the same value while ignoring NAs如何创建一个计数器,将重复分组为相同的值,同时忽略 NA
【发布时间】:2020-06-16 15:40:35
【问题描述】:

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

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

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

1,2,NA,3,4,4

作为结果,相同值的重复,具有相同的计数器。

感谢任何帮助。谢谢,

最好的

【问题讨论】:

  • 应该rex &lt;- c("Positive", NA, "Positive") 导致1, NA, 11, NA, 2??

标签: r


【解决方案1】:

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

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

如果rex &lt;- 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 &lt;- 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-09
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 2019-08-19
    • 2020-08-13
    • 2023-03-21
    相关资源
    最近更新 更多