Here is a function that can be called with a data set x
, a grouping variable and any number of columns. It returns a list of data.frames.
perc_table <- function(x, group, ...) {
cols <- list(...) |> unlist()
by(x[cols], x[[group]], \(x) {
apply(x, 2, \(y) {
tbl <- prop.table(table(y, useNA = "always")) |> as.data.frame()
tbl$Freq <- tbl$Freq*100
tbl
})
})
}
perc_table(mtcars, group = "am", "cyl", "gear", "carb")
#> x[[group]]: 0
#> $cyl
#> y Freq
#> 1 4 15.78947
#> 2 6 21.05263
#> 3 8 63.15789
#> 4 <NA> 0.00000
#>
#> $gear
#> y Freq
#> 1 3 78.94737
#> 2 4 21.05263
#> 3 <NA> 0.00000
#>
#> $carb
#> y Freq
#> 1 1 15.78947
#> 2 2 31.57895
#> 3 3 15.78947
#> 4 4 36.84211
#> 5 <NA> 0.00000
#>
#> ------------------------------------------------------------
#> x[[group]]: 1
#> $cyl
#> y Freq
#> 1 4 61.53846
#> 2 6 23.07692
#> 3 8 15.38462
#> 4 <NA> 0.00000
#>
#> $gear
#> y Freq
#> 1 4 61.53846
#> 2 5 38.46154
#> 3 <NA> 0.00000
#>
#> $carb
#> y Freq
#> 1 1 30.769231
#> 2 2 30.769231
#> 3 4 23.076923
#> 4 6 7.692308
#> 5 8 7.692308
#> 6 <NA> 0.000000
Created on 2023-08-22 with reprex v2.0.2