# [R] How to detect a sequence of NA values?

Richard Kwock richardkwock at gmail.com
Wed Jan 8 21:02:37 CET 2014

```Hey Arun,

That's a good point. You'd first need a non-NA element in the first
element (such as a 0) in order for that to work, which you can get
around by adding a 0 to the first element of the vector.

a1 <- c(NA,NA,NA,NA,1,NA,NA,2)
a2 <- c(1,NA,NA,NA,NA,1,NA,NA,2)

diff(which(!is.na(c(0,a1))))-1
# [1] 4 2

diff(which(!is.na(c(0,a2))))-1
# [1] 0 4 2

Richard

On Wed, Jan 8, 2014 at 11:43 AM, arun <smartpink111 at yahoo.com> wrote:
> Hi,
> If missing values are in the beginning
>
> a <- c(NA,NA,NA,NA,1,NA,NA,2)
> diff(which(!is.na(a)))-1
> #[1] 2
>
>
>
>  rl <- rle(is.na(a))
>  max(rl\$lengths[rl\$values])
> #[1] 4
>
> A.K.
>
>
>
>
> On Wednesday, January 8, 2014 12:56 PM, Richard Kwock <richardkwock at gmail.com> wrote:
> Another way:
>
> a = c(1,NA,NA,4,3,NA,NA,NA,NA,5)
>
> # find position of the non-NAs in the vector
> pos = which(!is.na(a))
>
> # this calculates the length by taking the differences between the
> non-NA positions.
> diff(pos)-1
>
> #get the max
> max(diff(pos)-1)
>
> Richard
>
>
> On Tue, Jan 7, 2014 at 7:36 PM, arun <smartpink111 at yahoo.com> wrote:
>> Hi,
>> Try:
>> rl <- rle(is.na(a))
>>  max(rl\$lengths[rl\$values])
>> #[1] 3
>>
>>
>> A.K.
>>
>>
>> Hi,
>>
>> I'd like to detect whether a vector contains a sequence of NA values of a certain length. So, for example, if I have a vector a =
>> c(1,NA,NA,4,NA,NA,NA,5); how can I find what the longest sequence of NAs is (in this case 3)?
>>
>> Note that this is different from simply summing the number of NA values in the vector (which would be 5 in this case)...
>>
>> Thanks for your help !
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help