【问题标题】:Group by count by a subgroup in R按 R 中的子组按计数分组
【发布时间】:2022-09-22 23:40:21
【问题描述】:

我这里有示例代码

df |>
  dplyr::group_by(label) |>
  dplyr::summarize(avg_col = mean(count_col, na.rm = TRUE),
                   med_col = median(count_col, na.rm  = TRUE),
                   n = n()) |>
  dplyr::arrange(desc(avg_col))

我想得到 count_col 为 1 的次数百分比。 我怎样才能在总结语句中做到这一点? 我首先需要过滤到 count_col ==1 而不是将其除以总数。

我不确定如何做到这一点。

  • prct = sum(count_col == 1) / n() * 100

标签: r dplyr


【解决方案1】:

我们可以在逻辑向量上使用mean 来获得百分比(* 100)

df |>
  dplyr::group_by(label) |>
  dplyr::summarize(perc_count_one = 100 * mean(count_col == 1, na.rm TRUE), 
                   avg_col = mean(count_col, na.rm = TRUE),
                   med_col = median(count_col, na.rm  = TRUE),
                   n = n()) |>
  dplyr::arrange(desc(avg_col))

【讨论】:

    猜你喜欢
    • 2022-07-22
    • 1970-01-01
    • 2017-05-09
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 2016-01-29
    相关资源
    最近更新 更多