无法使用magrittr forward pipe

时间:2017-01-15 06:58:10

标签: r magrittr

我有以下代码。 看起来非常简单,只是循环ARMA模型AR(1),MA(0)然后AR(1)MA(2)等各种组合。

load.or.install <- function(package.names) {
    is.installed <- function(mypkg) is.element(mypkg, installed.packages()[, 1])

    for (package.name in package.names) {
        if (!is.installed(package.name)) {
            install.packages(package.name)
        }
        library(package.name, character.only = TRUE, quietly = TRUE, verbose = FALSE)
    }
}

load.or.install(c("tseries", "forecast", "ggplot2", "dplyr", "magrittr", "rdatamarket"))

max.p <- 8 #  maximum number of AR terms
max.q <- 7 #  maximum number of MA terms
    #import data 
ausgdp <- as.ts(dmseries("http://data.is/1jDQwpr")[, 1]) %>% log() %>% diff(difference = 1)


model.orders <- as.matrix(expand.grid(AR = 0:max.p, DIF = 0, MA = 0:max.q))
models <- list()
1:nrow(model.orders) %>% {
    models[[.]] <- Arima(ausgdp, order = model.orders[.,], include.constant = T, method = "ML")
}

然而我收到以下错误信息。

Error in stats::arima(x = x, order = order, seasonal = seasonal, xreg = xreg,  : 
  'order' must be a non-negative numeric vector of length 3

如果我在循环外运行以下命令,它可以工作;

Arima(ausgdp, order = model.orders[1,], include.constant = T, method = "ML")

一旦它在model.orders[.,]的循环中就失败了 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

请注意运行以下内容时会发生什么。

1:nrow(model.orders) %>% {length(.)}

您实际上是在同时传递1:nrow(model.orders)中的所有元素,而不是逐一传递。

不是一次将model.orders子行化,然后将其传递给order,而是一次性获取所有行,从而提示错误。

您可以在管道后使用lapply获得所需的结果。

models <- 1:nrow(model.orders) %>% 
  lapply(., function(row_n){
    Arima(ausgdp, 
          order = as.vector(model.orders[row_n, ]), 
          include.constant = T, 
          method = "ML")
  })