Error in R: Inappropriate arguments. Not true?

this is my code:

#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") 

where censorship is my data table, including 200 (censored) y values ​​and 200 x values.

Everything works, but when I run 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 

I know what this means, but since x is a 200 by 2 matrix, and b [1: 2] is a 2 by 1 vector, what is wrong? I tried transferring both, as well as a vector of initial values, but nothing works. Can someone help me?

+5
source share
1 answer

I stumbled upon a similar problem today (the error of “inappropriate arguments”, although everything seemed OK), and the solution in my case was in the basic rules for matrix multiplication: that is, the number of matrix columns on the left should be the same as the number of matrix rows on the right = me had to switch the order in the multiplication equation. In other words, with matrix multiplication (as opposed to ordinary multiplication), A %*% B does not coincide with B %*% A

+6
source

Source: https://habr.com/ru/post/1234120/


All Articles