関数で必要なものが見つかるかもしれません?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
orを使用するか、パッケージを使用してed データ フレームで実行してから、元の形式に戻ります。これが例です。numcolwise
summarise
summarise
melt
reshape2
cast
それは次のようになります:
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"]))
これは、重み自体を除いて、すべての数値フィールドの加重平均を計算します。