简体   繁体   中英

R error: dims do not match the length of an object

I am currently trying to run some code (if you need to know the purpose to help me, ask me, but I'm trying to keep this question short). This is the code:

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
}

However, when I try to run the code:

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

I get the following error:

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

Traceback tells me that the error is occurring in the first for loop in the line:

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

Could someone point me to what I'm doing wrong? When I try to run this code step by step outside of the custom p.grm function, everything seems to work fine.

It is a common mistake. When you write the for loop and you want it from 1 to ncat -1 remember to write it as for (i in 1:(ncat-1)) instead of for(i in 1:ncat-1) they are completly different.

You may also add to the function something to return return(z) . Here it is the corrected code:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM