Calculate a series of weighted means in R for groups with different weightings

*爱你&永不变心* 提交于 2019-12-05 15:36:52

Try

library(data.table)
setDT(data)[, .(x1=weighted.mean(x1, w1), x2=weighted.mean(x2, w2)) , by = n]

Or as @thelatemail commented, we can use Map to loop over "x's", corresponding "w's" columns and call with a single weighted.mean

setDT(data)[, Map(weighted.mean, list(x1,x2), list(w1,w2)), by = n]

If there are many "x" and "w" columns, we can use grep to get the column names, mget to return the values inside the Map

setDT(data)[,  Map(weighted.mean, mget(grep('x', names(data), 
    value=TRUE)), mget(grep('w', names(data), value=TRUE))), by = n]

Try:

library(dplyr)
data %>% 
  group_by(n) %>% 
  summarise(x1 = weighted.mean(x1, w1), x2 = weighted.mean(x2, w2))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!