您应该尝试使用用户创建的函数。这是我想出的一个:
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))
希望对你有帮助