如何在 data.frame 中的所有列上使用 plyr 计算 weighted.mean?

how to calculate a weighted.mean with plyr on all columns in a data.frame?

只是好奇是否有我所缺少的偷偷摸摸的方法。

library(plyr)
library(data.table)

dfx <- data.frame(
  group = c(rep('A', 8), rep('B', 15), rep('C', 6)),
  sex = sample(c("M", "F"), size = 29, replace = TRUE),
  age = runif(n = 29, min = 18, max = 54) ,
  score = runif( n = 29 ) ,
  weight = sample( 0:1 , 29 , replace = TRUE )
)

dt_dfx <- as.data.table(dfx)

未加权均值比较

# mean of all columns not specified in by=
dt_dfx[ , lapply( .SD , mean ) , by = .(sex,group) ]

# here's how to match the data.table unweighted mean
ddply(dfx, .(group,sex), numcolwise(mean))

不确定如何使用 plyr

# weighted.mean of all columns not specified in by=
dt_dfx[ , lapply( .SD , weighted.mean , weight ) , by = .(sex,group) ]

# easy way to match the data.table weighted.mean?

谢谢大家

这是一个dplyr解决方案,希望对您有所帮助

dfx %>%
group_by( sex , group ) %>%
summarize_each( funs( weighted.mean( . , weight ) ) , -weight )