识别向量中的 NA 集 [英] Identify sets of NA in a vector

查看:63
本文介绍了识别向量中的 NA 集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个向量 x:

x <- c(NA, NA, 1, 2, NA, NA, 3, 4)

如何识别此向量中的 NA 集,即

How do I identify sets of the NAs within this vector, i.e.,

na_set <- c(1, 1, 0, 0, 2, 2, 0, 0)

我的最终目标是使用 dplyr 将它与数据框上的管道一起使用.所以,如果有兼容dplyr的功能就更好了.

My end goal is to use it with a pipe on a data frame using dplyr. So, if there's a function compatible with dplyr that's even better.

谢谢!

推荐答案

计算 is.na(x) 的游程编码,并用序列号或 0 替换值,然后反转回来.

Compute the run length encoding of is.na(x) and replace the values with sequence numbers or 0. Then invert back.

r <- rle(is.na(x))
r$values <- cumsum(r$values) * r$values
inverse.rle(r)
## [1] 1 1 0 0 2 2 0 0

这篇关于识别向量中的 NA 集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆