R错误:dims与对象的长度不匹配

时间:2018-03-14 13:34:47

标签: r runtime-error

我目前正在尝试运行一些代码(如果您需要了解帮助我的目的,请问我,但我试图保持这个问题简短)。这是代码:

par<-c(a=.5,b=rep(1.3,4))
est<-rep(TRUE,length(par))
ncat<-5
Theta<-matrix(c(-6,-5.8,-5.6,-5.4,-5.2,-5,-4.8,-4.6,-4.4,-4.2,-4,-3.8,-3.6,-3.4,-3.2,-3,-2.8,-2.6,-2.4,-2.2,-2,-1.8,-1.6,-1.4,-1.2,-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6,2.8,3,3.2,3.4,3.6,3.8,4,4.2,4.4,4.6,4.8,5,5.2,5.4,5.6,5.8,6))


p.grm<-function(par,Theta,ncat){
  a<-par[1]
  b<-par[2:length(par)]
  z<-matrix(0,nrow(Theta),ncat)
  y<-matrix(0,nrow(Theta),ncat)
  y[,1]<-1
  for(i in 1:ncat-1){
    y[,i+1]<-(exp(a*(Theta-b[i])))/(1+exp(a*(Theta-b[i])))
  }
  for(i in 1:ncat-1){
    z[,i]<-y[,i]-y[,i+1]
  }
  z[,ncat]<-y[,ncat]
  z
}

但是,当我尝试运行代码时:

p.grm(par=par,Theta=Theta,ncat=ncat)

我收到以下错误:

Error: dims [product 61] do not match the length of object [0]

Traceback告诉我错误发生在行的第一个for循环中:

y[,i+1]<-(exp(a*(Theta-b[i])))/(1+exp(a*(Theta-b[i])))

有人能指出我做错了什么吗?当我尝试在自定义p.grm函数之外逐步运行此代码时,一切似乎都正常。

1 个答案:

答案 0 :(得分:1)

这是一个常见的错误。当您编写for循环并希望将其从1发送到ncat -1时,请记住将其写为for (i in 1:(ncat-1))而不是for(i in 1:ncat-1),它们完全不同。

您还可以向函数添加要返回return(z)的内容。这是更正后的代码:

par<-c(a=.5,b=rep(1.3,4))
est<-rep(TRUE,length(par))
ncat<-5
Theta<-matrix(c(-6,-5.8,-5.6,-5.4,-5.2,-5,-4.8,-4.6,-4.4,-4.2,-4,-3.8,-3.6,-3.4,-3.2,-3,-2.8,-2.6,-2.4,-2.2,-2,-1.8,-1.6,-1.4,-1.2,-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6,2.8,3,3.2,3.4,3.6,3.8,4,4.2,4.4,4.6,4.8,5,5.2,5.4,5.6,5.8,6))


p.grm<-function(par,Theta,ncat){
  a<-par[1]
  b<-par[2:length(par)]
  z<-matrix(0,nrow(Theta),ncat)
  y<-matrix(0,nrow(Theta),ncat)
  y[,1]<-1
  for(i in 1:(ncat-1)){
    y[,i+1]<-(exp(a*(Theta-b[i])))/(1+exp(a*(Theta-b[i])))
  }
  for(i in 1:(ncat-1)){
    z[,i]<-y[,i]-y[,i+1]
  }
  z[,ncat]<-y[,ncat]
  return(z)
}


p.grm(par=par,Theta=Theta,ncat=ncat)