Fastest way to detect if vector has at least 1 NA?

后端 未结 6 1116
南旧
南旧 2020-12-23 14:50

What is the fastest way to detect if a vector has at least 1 NA in R? I\'ve been using:

sum( is.na( data ) ) > 0

But that

6条回答
  •  盖世英雄少女心
    2020-12-23 15:11

    One could write a for loop stopping at NA, but the system.time then depends on where the NA is... (if there is none, it takes looooong)

    set.seed(1234)
    x <- sample(c(1:5, NA), 100000000, replace = TRUE)
    
    nacount <- function(x){
      for(i in 1:length(x)){
        if(is.na(x[i])) {
          print(TRUE)
          break}
    }}
    
    system.time(
      nacount(x)
    )
    [1] TRUE
           User      System verstrichen 
           0.14        0.04        0.18 
    
    system.time(
      any(is.na(x))
    ) 
           User      System verstrichen 
           0.28        0.08        0.37 
    
    system.time(
      sum(is.na(x)) > 0
    )
           User      System verstrichen 
           0.45        0.07        0.53 
    

提交回复
热议问题