【发布时间】: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)
【问题讨论】: