Find columns with all missing values

后端 未结 8 466
Happy的楠姐
Happy的楠姐 2020-12-09 08:42

I am writing a function, which needs a check on whether (and which!) column (variable) has all missing values (NA, ). The following is fr

8条回答
  •  再見小時候
    2020-12-09 08:58

    In dplyr

    ColNums_NotAllMissing <- function(df){ # helper function
      as.vector(which(colSums(is.na(df)) != nrow(df)))
    }
    
    df %>%
    select(ColNums_NotAllMissing(.))
    
    example:
    x <- data.frame(x = c(NA, NA, NA), y = c(1, 2, NA), z = c(5, 6, 7))
    
    x %>%
    select(ColNums_NotAllMissing(.))
    

    or, the other way around

    Cols_AllMissing <- function(df){ # helper function
      as.vector(which(colSums(is.na(df)) == nrow(df)))
    }
    
    
    x %>%
      select(-Cols_AllMissing(.))
    

提交回复
热议问题