1
votes

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.

1
what is xm in your code?phiver
@phiver is is the design matrix X. it is a matrix with 2 cols, n rows.George
You need to pass that too maybe, mapply(func, b3, list(xm))RLave
@RLave ah. it's a typo. I'll edit the question, forgot to put it in the mapplyGeorge
It is enough to use sapply here, like this sapply(b3, func, xm).djhurio

1 Answers

2
votes

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)
}