pk_22
pk_22

Reputation: 390

Error in R: nonconformable 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 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?

Upvotes: 12

Views: 102540

Answers (2)

Pistachio Guoguo
Pistachio Guoguo

Reputation: 341

I offer one case in Principal Component Regression (PCR) in R, today I met this problem when tring to fit test data with model. it returned an error:

> pcr.pred = predict(pcr.fit, test.data, ncomp=6)
Error in newX %*% B[-1, , i] : non-conformable arguments
In addition: Warning message:

The problem was that, the test data has a new level that is previously not contained in the train data. To find which level has the problem:

cols = colnames(train)
for (col in cols){
  if(class(ori.train[[col]]) == 'factor'){
    print(col)
    print(summary(train[[col]]))
    print(summary(test[[col]]))
  }
}

You can check which annoying attributes has this new level, then you can replace this 'new' attribute with other common values, save the data with write.csv and reload it, and you can run the PCR prediction.

Upvotes: 0

Jan
Jan

Reputation: 171

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.

Upvotes: 17

Related Questions