Length of longest stretch of NAs in a column of data-frame object

梦想的初衷 提交于 2021-02-20 16:17:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!