r - 处理 R 中的缺失值,包括 NULL
问题描述
我正在尝试查找数据框中所有缺失值的总数,包括NA
"" 和NULL
每列。该summary()
函数只显示NA
值,甚至 VIM 包也是如此。
在PASWR::titanic3
数据集中,有空字符串的因子列在我的缺失分析中没有被捕获。
包含这些缺失值的计数的好方法是什么?此外,有没有办法显示缺失值的所有类型/频率?
提前致谢。
解决方案
您应该尝试使用用户创建的功能。这是我想出的一个:
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))
希望能帮助到你
推荐阅读
- ios - Swift - 在 UITableView 中向 UIButton 添加目标不起作用
- spring-boot - 使用 build.gradle 中 application.yml 文件中的值
- excel - Excel 频率与 IF 和
- javascript - 需要正则表达式帮助:模式几乎可以工作
- sql - SQL案例 | 如果
然后 - coldfusion - ColdFusion 中的 Square Checkout API - 'order.total_money.amount' 必须大于 1
- sql - 如何解决错误“操作数类型冲突:nvarchar 与使用 (encryption_type = ...) 加密的 nvarchar(32) 不兼容
- sql - 当引用另一个表时如何使用不同的配置单元
- javascript - 函数返回未定义而不是承诺中的整数?
- r - 具有随机效应和 lsoda 的非线性回归