Viewing all column names with any NA in R

前端 未结 5 854
一整个雨季
一整个雨季 2020-12-17 20:15

I need to get the name of the columns that have at least 1 NA.

df<-data.frame(a=1:3,b=c(NA,8,6), c=c(\'t\',NA,7))

I need to get \"b, c\"

5条回答
  •  暖寄归人
    2020-12-17 20:38

    Try the data.table version:

    library(data.table)
    setDT(df)
    names(df)[df[,sapply(.SD, function(x) any(is.na(x))),]]
    [1] "b" "c"
    

    Microbenchmarking using @akrun's code:

    set.seed(49)
    df1 <- as.data.frame(matrix(sample(c(NA,1:200), 1e4*5000, replace=TRUE), ncol=5000))
    setDT(df1)
    
    
    f1 <- function() {contains_any_na = sapply(df1, function(x) any(is.na(x)))
               names(df1)[contains_any_na]}
    
    f2 <- function() {colnames(df1)[!complete.cases(t(df1))] }
    f3 <- function() { names(df1)[!!colSums(is.na(df1))] }
    
    f4 <- function() { names(df1)[df1[,sapply(.SD, function(x) any(is.na(x))),]] }
    
    microbenchmark(f1(), f2(), f3(), f4(), unit="relative")   
    # Unit: relative
    #  expr       min        lq    median       uq      max neval
    #  f1()  1.000000  1.000000  1.000000 1.000000 1.000000   100
    #  f2() 10.459124 10.928821 10.955986 9.858967 7.069066   100
    #  f3()  3.323144  3.805183  4.159624 3.775549 2.797329   100
    #  f4() 10.108998 10.242207 10.121022 9.117067 6.576976   100
    

    @agstudy : This solution is similar in speed to colnames(df1)[!complete.cases(t(df1))].

提交回复
热议问题