as.double(y)出错:无法强制类型'关闭'到'' double'类型的向量在R

时间:2014-04-23 02:06:11

标签: r debugging optimization plot dataset

由于某些原因,在使y.hat成为一个单独的函数后,我的代码不再起作用了。有什么想法吗? 这是我收到的错误:

> 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'

这是我的代码:     要求(数据集)     数据(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")

1 个答案:

答案 0 :(得分:1)

您使用语句

覆盖了函数y.hat的定义
y.hat<-y.hat(beta,nhtemp)

我想你想做点什么

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