R中的汇总和加权均值 [英] Aggregate and Weighted Mean in R

查看:82
本文介绍了R中的汇总和加权均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按资产类别计算资产加权回报。为了我的一生,我不知道如何使用aggregate命令来做到这一点。

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.

我的数据框如下

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))


推荐答案

对于初学者来说, w =(dat $ return,dat $ assets))是语法错误。

For starters, w=(dat$return, dat$assets)) is a syntax error.

然后 plyr 做到了这一点容易一些:

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
> 

这篇关于R中的汇总和加权均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆