要替换的项目数不是替换长度的倍数-Datacamp

时间:2018-07-06 17:57:44

标签: r ggplot2

我遵循DataCamp中有关R的一些课程,有时,当我将数据从datacamp复制到R-studio时,我遇到了问题,但通常情况下,我会在这里找到答案,或者通常是在网上找到答案。但是,这次我无法理解什么是错误或如何解决。我从datacamp复制粘贴代码

# Compute cross-validated errors for up to 8 steps ahead

e <- matrix(NA_real_, nrow = 1000, ncol = 8)
for(h in 1:8)
  e[, h] <- tsCV(goog, forecastfunction = naive, h = h)

# Compute the MSE values and remove missing values

mse <- colMeans(e^2, na.rm = TRUE)

# Plot the MSE values against the forecast horizon

data.frame(h = 1:8, MSE = mse) %>%   ggplot(aes(x = h, y = MSE)) + geom_point()

当我将此代码添加到R-studio(包括所需的软件包)时,总是会出现以下错误:

**Error in e[, h] <- tsCV(goog, forecastfunction = naive, h = h) : 
  number of items to replace is not a multiple of replacement length**

有人知道为什么会这样吗?

2 个答案:

答案 0 :(得分:0)

这里的问题是,当h = 1时,tsCV仅在h = 2时返回一列,它将提供两列h = 1和h = 2,如果h = 8则将返回8列,h = 1,.. .h = 8。以下代码将解决该问题,但是我们将无法通过循环找到h = 1的值(因为tsCV(goog, forecastfunction = naive, h = 1)将成为向量,[,1]将成为an incorrect number of dimensions),因此我们将单独计算:

library(forecast)
library(fpp2)


e <- matrix(data = NA, nrow = 1000, ncol =8)
for(h in 2:8){


  e[, h] <- tsCV(goog, forecastfunction = naive, h = h)[,h]
  }


e[,1]<- tsCV(goog, forecastfunction = naive, h = 1)                                          

# Compute the MSE values and remove missing values

mse <- colMeans(e^2, na.rm = TRUE)

# Plot the MSE values against the forecast horizon

data.frame(h = 1:8, MSE = mse) %>%   ggplot(aes(x = h, y = MSE)) + geom_point()

请注意: tsCV代表forecast包中的时间序列交叉验证

goog是来自fpp2数据包的数据集

答案 1 :(得分:0)

设置tsCV(h = n)时,它将返回n列并计算所有值1:n。
您只需将代码更改为

# Compute cross-validated errors for up to 8 steps ahead
e <- matrix(NA_real_, nrow = 1000, ncol = 8)
e <- tsCV(goog, forecastfunction = naive, h = 8)

# Compute the MSE values and remove missing values
mse <- colMeans(e^2, na.rm = TRUE)

# Plot the MSE values against the forecast horizon
data.frame(h = 1:8, MSE = mse) %>%
ggplot(aes(x = h, y = MSE)) + geom_point()

如果您想进一步了解tsCV功能,请参见以下功能代码

function (y, forecastfunction, h = 1, window = NULL, ...) 
{
    y <- as.ts(y)
    n <- length(y)
    e <- ts(matrix(NA_real_, nrow = n, ncol = h))
    tsp(e) <- tsp(y)
    for (i in seq_len(n - 1)) {
        fc <- try(suppressWarnings(forecastfunction(subset(y, 
            start = ifelse(is.null(window), 1L, ifelse(i - window >= 
                0L, i - window + 1L, stop("small window"))), 
            end = i), h = h, ...)), silent = TRUE)
        if (!is.element("try-error", class(fc))) {
            e[i, ] <- y[i + (1:h)] - fc$mean
        }
    }
    if (h == 1) {
        return(e[, 1L])
    }
    else {
        colnames(e) <- paste("h=", 1:h, sep = "")
        return(e)
    }
}
<bytecode: 0x10e17fe70>
<environment: namespace:forecast>