Usually, when I count a column in a data frame, I use the count() function from the dplyr package.
library(dplyr)
mtcars %>%
count(cyl)
and
mtcars %>%
count(am)
and
mtcars %>%
count(gear)
etc...
Now I would like to count cyl, am, gear in one run.
Note: I don't mean
mtcars %>%
count(cyl, am, gear)
My working approach so far:
library(dplyr)
library(tidyr)
mtcars %>%
count(am) %>%
bind_rows(mtcars %>%
count(cyl)) %>%
bind_rows(mtcars %>%
count(gear)) %>%
pivot_longer(-n,
values_drop_na = TRUE) %>%
unite("variable", c("name", "value")) %>%
relocate(variable, n)
variable n
<chr> <int>
1 am_0 19
2 am_1 13
3 cyl_4 11
4 cyl_6 7
5 cyl_8 14
6 gear_3 15
7 gear_4 12
8 gear_5 5
I'm wondering if there's a more concise way to achieve this.
Perhaps pivot and count?
You can "clean up" the names if you want by pasting them together.