I am trying to create a summary table with only N and %s formatted like this.
data("mtcars")
am (N [%])
0 19 [59%]
1 13 [41%]
gear (N [%])
3 15 [46%]
4 12 [37.5%]
5 5 [15.6%]
carb (N [%])
1 7 [21.8%]
2 10 [31.2%]
3 3 [09.3%]
4 10 [31.2%]
6 1 [03.1%]
8 1 [03.1%]
Right now I am only thinking about table and prop.table but I am not sure how to generate the summary table like this efficiently. Any suggestion much appreciated. Thanks in advance.
Probably you can try the following approach as an example
mtcars %>%
select(am, gear, carb) %>%
lapply(\(x) {
as.data.frame(
table(x)
) %>%
mutate(perc = proportions(Freq) * 100)
})
which gives
$am
x Freq perc
1 0 19 59.375
2 1 13 40.625
$gear
x Freq perc
1 3 15 46.875
2 4 12 37.500
3 5 5 15.625
$carb
x Freq perc
1 1 7 21.875
2 2 10 31.250
3 3 3 9.375
4 4 10 31.250
5 6 1 3.125
6 8 1 3.125