【问题标题】:calculate the proportion for each category in tibble [duplicate]计算tibble中每个类别的比例[重复]
【发布时间】:2021-10-29 19:13:53
【问题描述】:

如何计算每个部分“是”的比例

library(dplyr)

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

tbl <- tibble(attendance, section)

【问题讨论】:

  • 使用基地:prop.table(table(tbl), 2)[2, ]

标签: r dplyr


【解决方案1】:
tbl %>%
  group_by(section) %>%
  summarise(prop = sum(attendance == "Yes")/ n())

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

【讨论】:

    【解决方案2】:

    你可以使用 -

    library(dplyr)
    tbl %>% group_by(section) %>% summarise(prop = mean(attendance == 'Yes'))
    
    #  section  prop
    #  <chr>   <dbl>
    #1 A         0.5
    #2 B         0.6
    

    或者在基础 R 中 -

    aggregate(attendance~section, tbl, function(x) mean(x == 'Yes'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 2020-07-29
      • 2021-02-15
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 2019-09-06
      相关资源
      最近更新 更多