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 looks like this
dat <- data.frame(company, fundname, assetclass, return, assets)
I'm trying to do something like (don't copy this, it's wrong):
aggregate(dat, list(dat$assetclass), weighted.mean, w=(dat$return, dat$assets))
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
>
A data.table
solution, will be faster than plyr
library(data.table)
DT <- data.table(dat)
DT[,list(wret = weighted.mean(return,assets)),by=assetclass]
## assetclass wret
## 1: A -0.05445455
## 2: E -0.56614312
## 3: D -0.43007547
## 4: B 0.69799701
## 5: C 0.08850954
This is also easily done with aggregate. It helps to remember alternate equations for a weighted mean.
rw <- dat$return * dat$assets
dat1 <- aggregate(rw ~ assetclass, data = dat, sum)
datw <- aggregate(assets ~ assetclass, data = dat, sum)
dat1$weighted.return <- dat1$rw / datw$assets
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With