获取向量中缺少值的游程长度 [英] Get length of runs of missing values in vector

查看:83
本文介绍了获取向量中缺少值的游程长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是聪明的(即不是循环)方式来获取向量中每个缺失值的长度?我的理想输出是一个长度相同的向量,其中每个缺失值都被缺失值的拼写的长度所取代,而缺失值就是它的一部分,而所有其他值都是0.

What's a clever (i.e., not a loop) way to get the length of each spell of missing values in a vector? My ideal output is a vector that is the same length, in which each missing value is replaced by the length of the spell of missing values of which it was a part, and all other values are 0's.

因此,对于像这样的输入

So, for input like:

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

我想要类似的输出:

y <- c(0,0,0,0,3,3,3,0,0,2,2)

推荐答案

使用rle的一个简单选项:

m <- rle(is.na(x))
> rep(ifelse(m$values,m$lengths,0),times = m$lengths)
[1] 0 0 0 0 3 3 3 0 0 2 2

这篇关于获取向量中缺少值的游程长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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