Domanda

For some reason after making y.hat a separate function my code doesn't work any more. Any thought on this? Here's the error I receive:

> source("y.hat.R")
 Time-Series [1:60] from 1912 to 1971: 49.9 52.3 49.4 51.1 49.4 47.9 49.8 50.9 49.3 51.9 ...
Error in as.double(y) : 
  cannot coerce type 'closure' to vector of type 'double'

And here's my code: require(datasets) data(nhtemp) str(nhtemp)

y.hat<-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]
  }
  return(y.hat)

}
mona.function <- function(beta, y=nhtemp){
  n<-length(y)
  y.hat<-y.hat(beta,nhtemp)
  sq.sum=0
  for (i in 2:n)
  {
    sq.sum = sq.sum + (y[i]-y.hat[i])^2

  }
  return(sq.sum/n)
}

opt.result=optimize(mona.function, c(0,1), maximum=FALSE)
y.hat(opt.result$minimum,nhtemp)
plot(nhtemp)
lines(ts(y.hat, start = start(nhtemp)[1], end = end(nhtemp)[1]), col = "red")

beta=0.1
y.hat<-y.hat(beta,nhtemp)
lines(ts(y.hat, start = start(nhtemp)[1], end = end(nhtemp)[1]), col = "green")

beta=0.9
y.hat<-y.hat(beta,nhtemp)
lines(ts(y.hat, start = start(nhtemp)[1], end = end(nhtemp)[1]), col = "blue")
È stato utile?

Soluzione

You overwrote the definition of the function y.hat with the statement

y.hat<-y.hat(beta,nhtemp)

I think you want to do something like

y.hat.value <- y.hat(beta,nhtemp)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top