7

I have a data frame with some columns with missing values. Is there a way (using dplyr) to efficiently calculate the percentage of each column that is missing i.e. NA. Sought of like a colSum equivalent. So I dont have to calculate each column percentage missing individually ?

3
  • 1
    You should provide a data object for testing.
    – IRTFM
    Commented Nov 4, 2015 at 2:48
  • 1
    colMeans(is.na(x)) (base R rather than dplyr) might work.
    – Ben Bolker
    Commented Nov 4, 2015 at 2:54
  • Your question is about dplyr. Calculate using dplyr. Am I missing something?
    – akrun
    Commented Nov 4, 2015 at 4:23

3 Answers 3

18

First, I created a test data for you:

a<- c(1,NA,NA,4)
b<- c(NA,2,3,4)
x<- data.frame(a,b)
x
#    a  b
# 1  1 NA
# 2 NA  2
# 3 NA  3
# 4  4  4

Then you can use colMeans(is.na(x)) :

colMeans(is.na(x))
#    a    b 
# 0.50 0.25 
2
  • 2
    Thanks to Ben Bolker comment.
    – user3710546
    Commented Nov 4, 2015 at 4:14
  • Thank you, will add data next time
    – MP61
    Commented Nov 4, 2015 at 4:23
17

We can use summarise_each

 library(dplyr)
 x %>% 
   summarise_each(funs(100*mean(is.na(.))))
8

Loving the concision of purrr::map for this type of thing:

x %>% map(~ mean(is.na(.)))

1
  • x %>% map(~ mean(is.na(.))) %>% keep(~ 1 %in% .) %>% names() This keeps only the columns who are all na.
    – mtelesha
    Commented Aug 28, 2018 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.