R中的错误:参数不一致.不对? [英] Error in R: nonconformable arguments. Not true?
问题描述
这是我的代码:
#define likelihood function (including an intercept/constant in the function.)
lltobit <- function(b,x,y) {
sigma <- b[3]
y <- as.matrix(y)
x <- as.matrix(x)
vecones <- rep(1,nrow(x))
x <- cbind(vecones,x)
bx <- x %*% b[1:2]
d <- y != 0
llik <- sum(d * ((-1/2)*(log(2*pi) + log(sigma^2) + ((y - bx)/sigma)^2))
+ (1-d) * (log(1 - pnorm(bx/sigma))))
return(-llik)
}
n <- nrow(censored) #define number of variables
y <- censored$y #define y and x for easier use
x1 <- as.matrix(censored$x)
x <- cbind(rep(1,n),x1) #include constant/intercept
bols <- (solve(t(x) %*% x)) %*% (t(x) %*% y) #compute ols estimator (XX) -1 XY
init <- rbind(as.matrix(bols[1:nrow(bols)]),1) #initial values
init
tobit1 <- optim(init, lltobit, x=x, y=y, hessian=TRUE, method="BFGS")
其中被检查的是我的数据表,包括y的200个(被检查的)值和x的200个值.
where censored is my data table, including 200 (censored) values of y and 200 values of x.
一切正常,但是运行optim命令时,出现以下错误:
Everything works, but when running the optim command, i get the following error:
tobit1 <- optim(init, lltobit, x=x, y=y, hessian=TRUE, method="BFGS")
Error in x %*% b[1:2] : non-conformable arguments
我知道这是什么意思,但是由于x是200 x 2的矩阵,而b [1:2]是2 x 1的向量,那出了什么问题?我尝试同时转置初始值向量和初始值向量,但没有任何效果.谁能帮我?
I know what it means, but since x is a 200 by 2 matrix, and b[1:2] a vector of 2 by 1, what goes wrong? I tried transposing both, and also the initial values vector, but nothing works. Can anyone help me?
推荐答案
我今天偶然发现了一个类似的问题(即使一切似乎都正常,不一致的参数"错误),而我的解决方案是针对以下问题的基本规则矩阵乘法:即左矩阵的列数量必须与右行的数量相同strong>矩阵=我必须在乘法方程式中切换顺序.
换句话说,在矩阵乘法中(不同于普通乘法),A %*% B
与B %*% A
不同.
I stumbled upon a similar problem today ("non-conformable arguments" error, even though everything seemed OK), and solution in my case was in basic rules for matrix-multiplication: i.e. number of columns of the left matrix must be the same as the number of rows of the right matrix = I had to switch order in multiplication equation.
In other words, in matrix multiplication (unlike ordinary multiplication), A %*% B
is not the same as B %*% A
.
这篇关于R中的错误:参数不一致.不对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!