I want to count the number of NA
values in a data frame column. Say my data frame is called df
, and the name of the column I am considering is
Try this:
length(df$col[is.na(df$col)])
User rrs answer is right but that only tells you the number of NA values in the particular column of the data frame that you are passing to get the number of NA values for the whole data frame try this:
apply(<name of dataFrame>, 2<for getting column stats>, function(x) {sum(is.na(x))})
This does the trick
Similar to hute37's answer but using the purrr
package. I think this tidyverse approach is simpler than the answer proposed by AbiK.
library(purrr)
map_dbl(df, ~sum(is.na(.)))
Note: the tilde (~
) creates an anonymous function. And the '.' refers to the input for the anonymous function, in this case the data.frame df
.
In the summary()
output, the function also counts the NA
s so one can use this function if one wants the sum of NA
s in several variables.
A quick and easy Tidyverse solution to get a NA
count for all columns is to use summarise_all()
which I think makes a much easier to read solution than using purrr
or sapply
library(tidyverse)
# Example data
df <- tibble(col1 = c(1, 2, 3, NA),
col2 = c(NA, NA, "a", "b"))
df %>% summarise_all(~ sum(is.na(.)))
#> # A tibble: 1 x 2
#> col1 col2
#> <int> <int>
#> 1 1 2
Try the colSums
function
df <- data.frame(x = c(1,2,NA), y = rep(NA, 3))
colSums(is.na(df))
#x y
#1 3