Date location class count
<date> <chr> <fct> <dbl>
1 2019-11-30 China total 1000
2 2019-11-30 China disney 1000
3 2019-11-30 China marvel 5
4 2019-11-30 Vietnam total 90
5 2019-11-30 Vietnam disney 80
6 2019-11-30 Vietnam marvel 10
以上是我的数据标题,我想将中国漫威的计数除以中国的总数,将越南的漫威除以越南的总数,依此类推(假设我们只有2019-11-30)
计算后,输出将如下所示:
Date location divided
2019-11-30 China 0.005
2019-11-30 Vietnam 0.111
它应该很简单,但却真的卡住了。执行此任务的好方法是什么?
发布于 2020-06-30 23:30:06
您可以取class == 'marvel'
指标的平均值,按计数加权
library(data.table)
setDT(df)
df[class != 'total', .(divided = weighted.mean(class == 'marvel', count)),
by = .(Date, location)]
# Date location divided
# 1: 2019-11-30 China 0.004975124
# 2: 2019-11-30 Vietnam 0.111111111
使用的数据:
df <- fread('
Date location class count
2019-11-30 China total 1000
2019-11-30 China disney 1000
2019-11-30 China marvel 5
2019-11-30 Vietnam total 90
2019-11-30 Vietnam disney 80
2019-11-30 Vietnam marvel 10
')
https://stackoverflow.com/questions/62660680
复制相似问题