在尝试制作预测误差的直方图时,我如何处理NaN?

时间:2017-04-17 22:59:24

标签: r

我是R的新手,并且一直在尝试从https://a-little-book-of-r-for-time-series.readthedocs.io/en/latest/src/timeseries.html#time-series-analysis学习时间序列分析。在中间,它概述了如何使用代码创建预测错误的直方图:

plotForecastErrors <- function(forecasterrors)
{
# make a histogram of the forecast errors:
mybinsize <- IQR(forecasterrors)/4
mysd   <- sd(forecasterrors)
mymin  <- min(forecasterrors) - mysd*5
mymax  <- max(forecasterrors) + mysd*3
# generate normally distributed data with mean 0 and standard deviation mysd
mynorm <- rnorm(10000, mean=0, sd=mysd)
mymin2 <- min(mynorm)
mymax2 <- max(mynorm)
if (mymin2 < mymin) { mymin <- mymin2 }
if (mymax2 > mymax) { mymax <- mymax2 }
# make a red histogram of the forecast errors, with the normally distributed data overlaid:
mybins <- seq(mymin, mymax, mybinsize)
hist(forecasterrors, col="red", freq=FALSE, breaks=mybins)
# freq=FALSE ensures the area under the histogram = 1
# generate normally distributed data with mean 0 and standard deviation mysd
myhist <- hist(mynorm, plot=FALSE, breaks=mybins)
# plot the normal curve as a blue line on top of the histogram of forecast errors:
points(myhist$mids, myhist$density, type="l", col="blue", lwd=2)
}

我的残差以两个NA值开始,我得到错误:

在quantile.default中出错(as.numeric(x),c(0.25,0.75),na.rm = na.rm ,:   如果'na.rm'为FALSE

,则不允许缺少值和NaN

那么如何让它跳过前两个NA值呢?我的残差也应该具有NA值吗?

1 个答案:

答案 0 :(得分:2)

您可以做的最简单的事情就是清除预报员中的NAs:

forecasterrors <- forecasterrors[!is.na(forecasterrors)]