快速提问,如何使用dplyr
计算群组权重?
例如,给定数据:
D = data.frame(cat=rep(LETTERS[1:2], each=2), val=1:4)
# cat val
# 1 A 1
# 2 A 2
# 3 B 3
# 4 B 4
期望的结果应该是:
# cat weight
# 1 A 0.3 # (1+2)/10
# 2 B 0.7 # (3+4)/10
比以下更简洁?
D %>%
mutate(total=sum(val)) %>%
group_by(cat) %>%
summarise(weight=sum(val/total))
答案 0 :(得分:8)
我把它写成
D <- data.frame(
cat = rep(LETTERS[1:2], each = 2),
val = 1:4
)
D %>%
group_by(cat) %>%
summarise(val = sum(val)) %>%
mutate(weight = val / sum(val))
您可以使用count()
(仅限dplyr&gt; = 0.3)和prop.table()
简化一点:
D %>%
count(cat, wt = val) %>%
mutate(weight = prop.table(n))