【发布时间】:2020-07-03 08:18:51
【问题描述】:
在我尝试学习dplyr 时,我想将每一行除以另一行,代表相应组的总数。
我用
生成了测试数据library(dplyr)
# building test data
data("OrchardSprays")
totals <- OrchardSprays %>% group_by(treatment) %>%
summarise(decrease = sum(decrease))
totals$decrease <- totals$decrease + seq(10, 80, 10)
totals$rowpos = totals$colpos <- "total"
df <- rbind(OrchardSprays, totals)
注意totals$decrease <- totals$decrease + seq(10, 80, 10) 行:为了这个问题,我假设每个treatment 都有一个额外的decrease,这在数据框的单行中没有观察到,而只是在“总" 每组的行。
我现在要做的是在数据框中添加另一列decrease_share,其中每行的decrease 值除以相应的treatment 组总数decrease value。
所以,对于head(df),我希望得到这样的输出
> head(df)
decrease rowpos colpos treatment treatment_decrease
1 57 1 1 D 0.178125
2 95 2 1 E 0.1711712
3 8 3 1 B 0.09876543
4 69 4 1 H 0.08603491
5 92 5 1 G 0.1488673
6 90 6 1 F 0.1470588
我的现实世界的例子有点复杂(更多组变量和更多级别),因此我正在dplyr 中寻找合适的解决方案。
【问题讨论】: