XTS Apply Family and a Multi Column XTS?

我的未来我决定 提交于 2019-12-21 17:55:47

问题


How do I use the apply family of functions, say apply.daily to a multivariate XTS?

So for example:

Time,a,b
...
2012-02-11 16:21:24 4.7258 7.7258
2012-02-11 16:26:25 4.9096 12.3796
2012-02-11 16:31:25 4.7904 2.2204
...

How would I use apply.daily and mean to the entire matrix by column. So the result would be a single time stamp for the day, the mean of a for the next column, and the mean of b for the column after that.

I would like to do this for arbitrary number columns (the amount of columns and names are not known -- all numeric of course).


回答1:


You could simply use colMeans to take the mean of every column:

library(quantmod)
getSymbols("SPY")
spy1 <- apply.weekly(SPY, colMeans)

You could also define an arbitrary function that uses apply over the columns of your object:

spy2 <- apply.weekly(SPY, function(x) apply(x,2,mean))
identical(spy1,spy2)
# [1] TRUE


来源:https://stackoverflow.com/questions/9242108/xts-apply-family-and-a-multi-column-xts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!