你可能會在?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
,或使用melt
編輯的數據幀與reshape2
pac kage,然後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"]))
將計算weighted-每個數字字段的平均值,不包括權重本身。
(?你知道你必須ddply'的'輸出分配到的東西,吧) – smci