Pregunta

I have the following code but lines() doesn't draw anything on the plot I've created by plot.ts(nhtemp). I don't want to use holtwinters function.

require(datasets)
data(nhtemp)
str(nhtemp)
mona.function <- function(beta, y=nhtemp){
  y.hat=numeric(length(y))
  y.hat[1]=y[1]
  y.hat[2]=y[2]
  for (i in 3:length(y))
  {
    y.hat[i]=beta*y[i-1]+(1-beta)*y.hat[i-1]
  }
  sq.sum=0
  for (i in 2:length(y))
  {
    sq.sum = sq.sum + (y[i]-y.hat[i])^2

  }
  plot.ts(nhtemp)
  lines(y.hat,col="red")
  return(sq.sum/length(y))
}
opt.result=optimize(mona.function, c(0,1), maximum=FALSE)

This is the figure I have a result: enter image description here

And this is the plot I am expected to achieve: enter image description here

¿Fue útil?

Solución

You can plot using

lines(ts(y.hat, start = start(nhtemp)[1], end = end(nhtemp)[1]), col = "red")

This way, you construct a time series that starts and ends the same way nhtemp does.

Otros consejos

you can try :

x <- attributes(nhtemp)$tsp
x <- seq(x[1], x[2], by=x[3])
lines(x, y.hat,col="red")

hth

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top