Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in R: nonconformable arguments. Not true?

Tags:

r

vector

matrix

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 censored is my data table, including 200 (censored) values of y and 200 values of x.

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

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?

like image 479
pk_22 Avatar asked Oct 20 '15 12:10

pk_22


People also ask

How do you multiply matrices in R?

To multiply two matrices by elements in R, we would need to use one of the matrices as vector. For example, if we have two matrices defined by names M1 and M2 then the multiplication of these matrices by elements can be done by using M1*as. vector(M2).

How do you calculate matrices in R?

In R there is no base function to calculate the rank of a matrix but we can make use of the qr function, which in addition to calculating the QR decomposition, returns the rank of the input matrix. An alternative is to use the rankMatrix function from the Matrix package.


1 Answers

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.

like image 64
Jan Avatar answered Oct 18 '22 15:10

Jan