问题
I want to write a code that finds the length of longest continuous stretch of NA values in a column of a data-frame object.
>> 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()?
回答1:
Using base R we could create a function
longestNAstrech <- function(x) {
with(rle(is.na(x)), max(lengths[values]))
}
longestNAstrech(df[, 1])
#[1] 3
longestNAstrech(df[, 2])
#[1] 2
来源:https://stackoverflow.com/questions/54501885/length-of-longest-stretch-of-nas-in-a-column-of-data-frame-object