我是 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))
编辑:如果要对多列进行操作,请使用colwise
或numcolwise
而不是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/