0

How can I calculate the proportion of "yes" for each section

library(dplyr)

attendance <- c("No", "Yes", "No", "Yes", "Yes", "No", "Yes")
section <- c("A", "A", "B", "B", "B", "B", "B")

tbl <- tibble(attendance, section)
SiH
  • 1,378
  • 4
  • 18

2 Answers2

2
tbl %>%
  group_by(section) %>%
  summarise(prop = sum(attendance == "Yes")/ n())

  section  prop
  <chr>   <dbl>
1 A         0.5
2 B         0.6
Park
  • 14,771
  • 6
  • 10
  • 29
1

You can use -

library(dplyr)
tbl %>% group_by(section) %>% summarise(prop = mean(attendance == 'Yes'))

#  section  prop
#  <chr>   <dbl>
#1 A         0.5
#2 B         0.6

Or in base R -

aggregate(attendance~section, tbl, function(x) mean(x == 'Yes'))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213