I\'m trying to calculate asset-weighted returns by asset class. For the life of me, I can\'t figure out how to do it using the aggregate command.
My data frame look
For starters, w=(dat$return, dat$assets)) is a syntax error.
And plyr makes this a little easier:
> set.seed(42) # fix seed so that you get the same results
> dat <- data.frame(assetclass=sample(LETTERS[1:5], 20, replace=TRUE),
+ return=rnorm(20), assets=1e7+1e7*runif(20))
> library(plyr)
> ddply(dat, .(assetclass), # so by asset class invoke following function
+ function(x) data.frame(wret=weighted.mean(x$return, x$assets)))
assetclass wret
1 A -2.27292
2 B -0.19969
3 C 0.46448
4 D -0.71354
5 E 0.55354
>