首页 > 解决方案 > 处理 R 中的缺失值,包括 NULL

问题描述

我正在尝试查找数据框中所有缺失值的总数,包括NA"" 和NULL每列。该summary()函数只显示NA值,甚至 VIM 包也是如此。

PASWR::titanic3数据集中,有空字符串的因子列在我的缺失分析中没有被捕获。

包含这些缺失值的计数的好方法是什么?此外,有没有办法显示缺失值的所有类型/频率?

提前致谢。

标签: r

解决方案


您应该尝试使用用户创建的功能。这是我想出的一个:

library(tidyverse)

test_function <- function(vector){
    ##The ifelse returns TRUE if the element in the vector is NA, NULL, or ""
    x <- ifelse(is.na(vector)|vector == ""|is.null(vector), TRUE, FALSE)

    ##Returns the sum of boolean vector (FALSE = 0, TRUE = 1)
    return(sum(x))
}

要将函数应用于数据帧,您可以使用任何 apply 函数,但我建议使用 sapply,因为它返回一个向量。

##Create a data frame with mock data

test_df <- tibble(x = c(NA, NA, NA, "","",1,2,3),
   y = c(NA, "","","","","","",1),
   z = c(0,0,0,0,0,0,0,0))

##Assign the result to a new variable
 total_missing_by_column <- sapply(test_df, test_function)

##You can also build a data frame with the variables and the total missing

tibble(variable = colnames(test_df),
   total_missing = sapply(test_df, test_function))

希望能帮助到你


推荐阅读