【问题标题】:Handle missing values including NULL in R处理 R 中的缺失值,包括 NULL
【发布时间】:2018-10-28 22:39:16
【问题描述】:

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

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

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

提前致谢。

【问题讨论】:

  • 在使用summary()之前,您可以简单地将所有形式的缺失值转换为NA

标签: r


【解决方案1】:

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

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))

希望对你有帮助

【讨论】:

    【解决方案2】:

    简单地转换 NA 以外的缺失值
    df[df %in% c("NULL", "")] <- NA
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-23
      • 2021-08-10
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      相关资源
      最近更新 更多