suppressPackageStartupMessages(library("dplyr"))
# Duplicate mtcars dataset as example
mtcars_na <- mtcars
# Add in some missing data
mtcars_na[8, c(1, 3, 4)] <- NA
mtcars_na[9, c(1, 2, 3)] <- NA
# In base R
vapply(mtcars_na, function(x) {
100 * sum(is.na(x), na.rm = TRUE) / length(x)
}, FUN.VALUE = double(1L))
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> 6.250 3.125 6.250 3.125 0.000 0.000 0.000 0.000 0.000 0.000 0.000
# Using tidyverse approach
# Specify the function you want applied to each column
fns <- list(pct_missing = ~ 100 * sum(is.na(.), na.rm = TRUE) / length(.))
# For all columns
(mtcars_summary <- mtcars_na %>%
summarise(across(, .fns = fns)))
#> mpg_pct_missing cyl_pct_missing disp_pct_missing hp_pct_missing
#> 1 6.25 3.125 6.25 3.125
#> drat_pct_missing wt_pct_missing qsec_pct_missing vs_pct_missing
#> 1 0 0 0 0
#> am_pct_missing gear_pct_missing carb_pct_missing
#> 1 0 0 0
Created on 2021-10-02 by the reprex package (v2.0.1)