rmatrixcbind

Why can I not multiply these two matrices of same dimensions?


I am trying to create a plot for my LCA covariate probabilities as described here . I have my probabilities from the covariate (a 6-level ordinal variable) that are as follows:

often <- as.data.frame(cbind(V1=c(13, 11, 12, 13, 12, 14), 
                       V2=c(-0.1, -0.8, -0.2, -0.4, -0.5, -0.3)))

rownames(often) <- c("(Intercept)", "sui_thoughts_often2", "sui_thoughts_often3",
                     "sui_thoughts_often4", "sui_thoughts_often5", "sui_thoughts_often6")


often <- as.matrix(often)

The next section of the code is multiplying two matrices, the 'often' one and the created 'pidmat' one.

pidmat <- cbind(1, c(1:6))
exb <- exp(pidmat %*% often)

When I try to execute the second line, this error appears:

Error in pidmat %*% often : non-conformable arguments

even though the matrices have the same dimensions?

I tried to manipulate the dimensions of 'pidmat' matrix but to no avail, error message stays same


Solution

  • Because for matrix dot products you need to match the number of columns from the first matrix with the number of rows of the second.

    In the case of matrix dot product, you need to transpose the often matrix and then multiply. This gives you a 6x6 matrix.

    exb <- exp(pidmat %*% t(often))
    

    If the intention is to do element-wise multiplication. Then this gives you a 6x2 matrix.

    exb <- exp(pidmat * often)