# How to get group-wise count?

I want to get the group-wise count of numbers.
In the below data, there is 0,2,4,5,6. I would like to get the count of these scores gender-wise. Like, for males, how many zeros, twos and fours appear.

``````library(tidyverse)
tibble::tribble(
~child_id,  ~gender, ~q1_score,
"PEN001",   "male",        0L,
"PEN002",   "male",        0L,
"PEN003", "female",        2L,
"PEN004", "female",        4L,
"PEN005",   "male",        2L,
"PEN006",   "male",        6L,
"PEN007", "female",        6L,
"PEN008",   "male",        5L
)
#> # A tibble: 8 x 3
#>   child_id gender q1_score
#>   <chr>    <chr>     <int>
#> 1 PEN001   male          0
#> 2 PEN002   male          0
#> 3 PEN003   female        2
#> 4 PEN004   female        4
#> 5 PEN005   male          2
#> 6 PEN006   male          6
#> 7 PEN007   female        6
#> 8 PEN008   male          5
``````

Created on 2022-01-29 by the reprex package (v2.0.1)

dat1 <- structure(list(child_id = c("PEN001", "PEN002", "PEN003", "PEN004",
"PEN005", "PEN006", "PEN007", "PEN008"), gender = c("male", "male",
"female", "female", "male", "male", "female", "male"), q1_score = c(0L,
0L, 2L, 4L, 2L, 6L, 6L, 5L)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -8L))

with(dat1, table(gender, q1_score))

I am able to get the count, but as it is a table, I am not able to mutate. i want to get the percentage of each value. For example, among males, xx% gave the right answer. Is that possible?

``````(dat2 <-   with(dat1, prop.table(table(gender, q1_score), 1)))

as.data.frame.matrix(dat2)  # easier to work with
``````

Or perhaps

``````dat1 %>% group_by(gender, q1_score) %>%
summarise(perc = sum(q1_score / 100))
``````

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.