Aggregate and Weighted Mean in R

前端 未结 4 2101
迷失自我
迷失自我 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:27

    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
    

提交回复
热议问题