我想编写一个代码,找到数据框对象列中最长连续拉伸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()?
使用base R我们可以创建一个函数
longestNAstrech <- function(x) {
with(rle(is.na(x)), max(lengths[values]))
}
longestNAstrech(df[, 1])
#[1] 3
longestNAstrech(df[, 2])
#[1] 2