【问题标题】:Creating percentages for each group using dply [duplicate]使用 dply 为每个组创建百分比 [重复]
【发布时间】:2020-07-14 17:25:30
【问题描述】:

所以我有一个如下的df

df <- structure(list(Reportable = c(0, 0, 0, 0, 1, 1, 1, 1, NA), 
    Stakeholder = c("1", "3", "4", "5", "1", "3", "4", "5", "5"
    ), count = c(68L, 154L, 241L, 132L, 309L, 203L, 403L, 215L, 
    1L)), row.names = c(NA, -9L), groups = structure(list(FRA.Reportable = c(0, 
1, NA), .rows = structure(list(1:4, 5:8, 9L), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = c(NA, 3L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

我想创建一个名为pct 的新变量,它显示组内每个组的百分比。因此,当 Stakeholder = 1 时,Reportable 中的 0 和 1 的总和应为 100%。我尝试使用以下方法,但计算不正确

df %>%
  mutate(pct = percent(count/sum(count))) 

所以基本上给定利益相关者中的所有条目的总和应为 100%。

这最终会在这里使用:

ggplot(df, aes(fill=as.factor(Reportable), y=count, x=as.factor(Stakeholder), label = pct)) + 
  geom_bar(position="dodge", stat="identity")+
  labs(x = "Stakeholder", y = "Count")+
  geom_text(position = position_dodge(width = .9),    # move to center of bars
            vjust = -0.5,    # nudge above top of bar
            size = 3) 

【问题讨论】:

    标签: r dplyr grouping


    【解决方案1】:

    使用dplyr::group_by

    df %>% 
      group_by(Stakeholder) %>% 
      mutate(pct = count/sum(count))
    

    返回

    # A tibble: 9 x 4
    # Groups:   Stakeholder [4]
      Reportable Stakeholder count     pct
           <dbl> <chr>       <int>   <dbl>
    1          0 1              68 0.180  
    2          0 3             154 0.431  
    3          0 4             241 0.374  
    4          0 5             132 0.379  
    5          1 1             309 0.820  
    6          1 3             203 0.569  
    7          1 4             403 0.626  
    8          1 5             215 0.618  
    9         NA 5               1 0.00287
    

    【讨论】:

      猜你喜欢
      • 2022-12-09
      • 1970-01-01
      • 2023-01-26
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      相关资源
      最近更新 更多