一列数据帧对象中最长的NA长度

Rit*_*wal 5 r

我想编写一个代码,以找到数据帧对象的列中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()?
Run Code Online (Sandbox Code Playgroud)

Ron*_*hah 3

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

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

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

longestNAstrech(df[, 2])
#[1] 2
Run Code Online (Sandbox Code Playgroud)