Search code examples
rmatrixmatrix-multiplication

Non-conformable arguments when using mapply


I have a function func that looks like this:

func<- function(beta,X){
  res <-  t(beta) %*% t(X) %*% X %*% beta
  return(res)
}

where X = design matrix and I have two matrices

b1 <- matrix(data = c(0.8, 3.6), nrow = 2, ncol = 1)
b2 <- matrix(data = c(1.56, 0.27), nrow = 2, ncol = 1)

when I call the function on each matrix it works fine, and produces a result.

func(b2,xm)
         [,1]
[1,] 213.6931

func(b1,xm)
         [,1]
[1,] 23138.99

However when I add these two matrices to a list, and try calling func using mapply I get a non-conformable arguments error.

b3 <- list(b1,b2)
mapply(func, c, X=xm)
#Error in t(beta) %*% t(X) : non-conformable arguments

I cannot understand why this happens. Any help would be greatly appreciated.


Solution

  • Just pass xm as list()

    mapply(func, b3, list(xm))
    [1] 390.5600  23.2569
    

    Data:

    xm <- matrix(1:4, ncol=2,nrow=2)
    b1 <- matrix(data = c(0.8, 3.6), nrow = 2, ncol = 1)
    b2 <- matrix(data = c(1.56, 0.27), nrow = 2, ncol = 1)
    b3 <- list(b1,b2)
    
    func<- function(beta,X){
      res <-  t(beta) %*% t(X) %*% X %*% beta
      return(res)
    }