With tidyverse in R there is something similar as colSums(is.na(df))?

Viewed 173

In tidyverse(dplyr) there is something similar like:

colSums(is.na(airquality)) ?

In other words how can I have a dataframe with one row summarising the number of NA values from each column?

I though about to use summarise. But how can I do this?

Any help?

Thanks

3 Answers

You can summarise across all columns, e.g. count the number of NA:

library(haven)
temp <- tempfile()
download.file("https://www.diw.de/documents/dokumentenarchiv/17/diw_01.c.412698.de/soep_lebensz_en.zip",temp)
soep <- read_dta(unz(temp, "soep_lebensz_en.dta"))
unlink(temp)

colSums(is.na(soep))

    id       year        sex  education    no_kids health_org satisf_org health_std satisf_std 
     0          0          0       1468        906         15          0         15          0 

library(tidyverse)
soep %>%
   summarise(across(everything(), ~ sum(is.na(.))))

# A tibble: 1 x 9
     id  year   sex education no_kids health_org satisf_org health_std satisf_std
  <int> <int> <int>     <int>   <int>      <int>      <int>      <int>      <int>
1     0     0     0      1468     906         15          0         15          0

You may try this:

library(tidyverse)
airquality %>% 
  map_dbl(~sum(is.na(.)))

or as suggested by Thomas in comments

airquality %>% is.na %>% map_dbl(sum)

The dplyr equivalent of colSums is summarize(across(everything(), sum)). We can add the is.na like this:

summarize(across(everything(), ~ sum(is.na(.))))

This will return a data frame, and will play well with group_by, which might be nice.

Related