本文介绍了rollapply() 是否允许调用函数的结果数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

# Loading packages

require(forecast)
require(quantmod)

# Loading OHLC xts object

getSymbols('SPY', from = '1950-01-01')

# Selecting weekly Close prices

x <- Cl(to.weekly(SPY))

# ARIMA(p,d,q) estimation and forecasting function

a.ari.fun <- function(x) {

  a.ari <- auto.arima(x = x, d = 1, max.p = 50, max.q = 50, max.P = 50,
                      max.Q = 50, ic = 'aic', approximation = TRUE)
  fore <- forecast.Arima(object = a.ari, h = 4, level = c(.9))
  supp <- tail(fore$lower, 1)
  rest <- tail(fore$upper, 1)
  return(c(supp, rest))

}

# Roll apply ARIMA(p,d,q) in rolling window

rollapplyr(data = tail(x, 800), width = 750, FUN = a.ari.fun)

此代码返回一个错误,因为

This code returns me an error because of

return(c(supp, rest))

在我写的a.ari.fun()函数的末尾;我确信这一点,因为如果 a.ari.fun() 只返回

at the end of a.ari.fun() function I wrote; I'm sure about that because if a.ari.fun() returns just

return(rest)

效果很好.

我必须如何安排 a.ari.fun() 以获得适合 rollapplyr() 的对象?

How do I have to arrange the a.ari.fun() in order to obtain an object suitable to rollapplyr()?

推荐答案

看起来使用 by.column=FALSE 会满足您的要求.

It looks like using by.column=FALSE will give what you request.

tail(rollapplyr(data = as.zoo(x), width = 750, FUN = a.ari.fun, by.column=FALSE))

2012-07-13 126.0730 145.8036
2012-07-20 126.1342 145.8616
2012-07-27 128.9303 148.6576
2012-08-03 129.7640 149.4975
2012-08-10 130.5752 150.2954
2012-08-17 132.3789 152.0963

多亏了 @JoshuaUlrich 的一些修补,现在可以使用 rollapply.xts,因此您不必转换为 zoo.此外,rollapply.xts 现在注册在 xts 包中,而不是 PerformanceAnalytics,因此无论是否PerformanceAnalytics 已加载.您将需要 xts 的正在开发版本——Rev. 765 或更高版本——位于 R-Forge.

Thanks to some patching from @JoshuaUlrich, this now works with rollapply.xts,so you do not have to convert to zoo. Also, rollapply.xts is now registered in the xts package instead of PerformanceAnalytics, so you will get the same results regardless of whether or not PerformanceAnalytics is loaded. You'll need the under development version of xts -- Rev. 765 or later -- which is on R-Forge.

rollapplyr(x, 750, a.ari.fun, by.column=FALSE)

这篇关于rollapply() 是否允许调用函数的结果数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:57