R 中的聚合和加权平均值
我正在尝试按资产类别计算资产加权回报。对于我的一生,我无法弄清楚如何使用聚合命令来做到这一点。
我的数据框看起来像这样,
dat <- data.frame(company, fundname, assetclass, return, assets)
我正在尝试做类似的事情(不要复制这个,这是错误的):
aggregate(dat, list(dat$assetclass), weighted.mean, w=(dat$return, dat$assets))
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))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用聚合也可以轻松完成此操作。它有助于记住加权平均值的替代方程。
This is also easily done with aggregate. It helps to remember alternate equations for a weighted mean.
最近发布的
collapse
包通过提供一整套 快速统计函数在 C++ 内部执行分组和加权计算:The recently released
collapse
package provides a fast solution to this and similar problems (using weighted median, mode etc.) by providing a full set of Fast Statistical Functions performing grouped and weighted computations internally in C++:对于初学者来说,
w=(dat$return, dat$assets))
是一个语法错误。plyr 使这变得更容易一些:
For starters,
w=(dat$return, dat$assets))
is a syntax error.And plyr makes this a little easier:
data.table
解决方案比plyr
更快A
data.table
solution, will be faster thanplyr