r - 如何创建一个计数器,将重复分组为相同的值,同时忽略 NA
问题描述
我的数据框有超过 5000 行的模拟。我的问题是这样的
rex <- c("Positive", "Negative", NA, "Positive", "Negative", "Negative")
我想创建一个返回的计数器:
1,2,NA,3,4,4
结果,在重复相同值的情况下,具有相同的计数器。
感谢任何帮助。谢谢,
最好的
解决方案
在这里我们可以使用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
推荐阅读
- android - 使用 firebaseui 登录 Facebook 不起作用 errorCode: 100, subErrorCode: 33, errorType: GraphMethodException
- python - Django 使用旧目录填充新项目
- javascript - 如何使用 Puppeteer 检查元素是否存在于异步/等待中
- javascript - 尝试创建 instagram 机器人,但不断收到语法错误?
- java - Android:如何将高度设置为 wrap_content?
- c# - 如何将此 VB.net 函数转换为 C#?
- c# - 如何将我的连接字符串表单保存到应用程序配置文件?
- python - Python 请求 / urllib / selenium 不解析整个网页 HTML
- html - 当字段为空时,如何在输入字段内显示字体真棒图标?
- java - Spring Integration DSL 自定义错误通道问题与 Executor