Aggregate and Weighted Mean in R

前端 未结 4 2080
迷失自我
迷失自我 2020-12-06 06:04

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

4条回答
  •  再見小時候
    2020-12-06 06:20

    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
    > 
    

提交回复
热议问题