R: how to sum the number of NA in each data.frame column

To calculate the number of NAs in the entire data.frame array, I can use sum(is.na(df), however, how can I calculate the number of NAs in each column of a large data.frame? I tried apply(df, 2, function (x) sum(is.na(df$x)), but it didn’t work.

+4
source share
3 answers

You can try:

colSums(is.na(df))
#  V1 V2 V3 V4 V5 
#   2  4  2  4  4 

data

set.seed(42)
df <- as.data.frame(matrix(sample(c(NA,0:4), 5*20,replace=TRUE), ncol=5))
+14
source

You can use sapply:

sapply(X = df, FUN = function(x) sum(is.na(x)))
+1
source

Try:

apply(df, 2, function(x) length(which(is.na(x))))
+1
source

All Articles