[英]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: Traceback告诉我错误发生在该行的第一个for循环中:
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.
当我尝试在自定义p.grm函数之外逐步运行此代码时,一切似乎都能正常运行。
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. 当您编写
for
循环并希望它从1
到ncat -1
请记住按for (i in 1:(ncat-1))
而不是for(i in 1:ncat-1)
它们完全不同。
You may also add to the function something to return return(z)
. 您也可以在函数中添加返回
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.