r - 如何使用 ddply 获取数据框中类的加权平均值?

标签 r plyr reshape weighted-average summarization

我是 plyr 的新手,想采用类中值的加权平均值来 reshape 多个变量的数据框。使用以下代码,我知道如何对一个变量执行此操作,例如 x2:

set.seed(123)
frame <- data.frame(class=sample(LETTERS[1:5], replace = TRUE),
                    x=rnorm(20), x2 = rnorm(20), weights=rnorm(20))
ddply(frame, .(class),function(x) data.frame(weighted.mean(x$x2, x$weights)))       

但是,我希望代码为 x 和 x2(以及框架中的任意数量的变量)创建一个新的数据框。有人知道怎么做这个吗?谢谢

最佳答案

您可能会在 ?summarise 函数中找到您想要的内容。我可以使用 summarise 复制您的代码,如下所示:

library(plyr)
set.seed(123)
frame <- data.frame(class=sample(LETTERS[1:5], replace = TRUE), x=rnorm(20), 
                    x2 = rnorm(20), weights=rnorm(20))
ddply(frame, .(class), summarise, 
      x2 = weighted.mean(x2, weights)) 

要对 x 也执行此操作,只需添加要传递到 summarise 函数的行:

ddply(frame, .(class), summarise, 
      x = weighted.mean(x, weights),
      x2 = weighted.mean(x2, weights)) 

编辑:如果要对多列进行操作,请使用colwisenumcolwise 而不是summarise,或者使用 reshape2 包对 melt 数据框进行 summarise,然后 cast 返回原始形式. Here's an example.


那会给出:

wmean.vars <- c("x", "x2")

ddply(frame, .(class), function(x)
      colwise(weighted.mean, w = x$weights)(x[wmean.vars]))

最后,如果您不想指定 wmean.vars,您还可以:

ddply(frame, .(class), function(x)
      numcolwise(weighted.mean, w = x$weights)(x[!colnames(x) %in% "weights"]))

这将为每个数字字段计算加权平均值,不包括权重本身。

关于r - 如何使用 ddply 获取数据框中类的加权平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18392408/

相关文章:

r - 将模拟泊松分布添加到 ggplot

r - 如何使用 CSV 时间数据在 R 中创建直方图?

r - 在 R 中将行拆分为列

通过 id 和事件强度预测(总和) reshape

pytorch - -1 在 pytorch View 中是什么意思?

r - 如何在ggplot2中指定图形的大小而与轴标签无关

python - 传递超过 23 个输入文件时 gdal_calc amin 失败

r - 在组内排序的 Lollipop 图

使用layout()进行绘图的R代码在逐行执行时有效,但在封装在函数中时无效

R - 加快大致日期匹配。 idata.frame?