数据框对象列中最长的NA的长度

问题描述 投票:4回答:1

我想编写一个代码,找到数据框对象列中最长连续拉伸NA值的长度。

>> df   
      [,1] [,2] 
[1,]    1    1   
[2,]   NA    1   
[3,]    2    4   
[4,]   NA    NA   
[6,]    1    NA   
[7,]   NA    8
[8,]   NA    NA
[9,]   NA    6
# e.g.
>> longestNAstrech(df[,1])
>> 3
>> longestNAstrech(df[,2])
>> 2
# What should be the length of longestNAstrech()?
r
1个回答
2
投票

使用base R我们可以创建一个函数

longestNAstrech <- function(x) {
  with(rle(is.na(x)), max(lengths[values]))  
}

longestNAstrech(df[, 1])
#[1] 3

longestNAstrech(df[, 2])
#[1] 2
© www.soinside.com 2019 - 2024. All rights reserved.