Search code examples
rloopsmatrixapplycustom-function

Applying/looping a customized function based on multiple lists/matrices in R


I have four large lists that I converted to matrices using this function:

array(as.matrix(unlist(mat2)), dim=c(3, 80, 100))

I have unlisted the list to convert it to a matrix form (not sure if needed, but the object.size is significantly smaller as a matrix). If it's easier to work with lists, please speak out. The matrices/lists have 132 elements, but let's just assume 100 here for simplicity.

mat1

num [1:80, 1:100] 0.00669 0.00603 0.00895 0.00771 0.01533 ...

mat2

 num [1:80, 1:80, 1:100] 0.0033 -0.00474 -0.00261 0.00587 -0.00599 ...

mat3

num [1:3, 1:80, 1:100] 0.0159 -0.0131 -0.0131 -0.0656 0.0554 ...

mat4

 num [1:10, 1:3] 0.00545 0.01043 0.00563 0.00431 0.00464 ...

Here is my function:

customfunction <- function
(
  mat1,         # num [1:80, 1:100]
  mat2,         # num [1:80, 1:80, 1:100]
  mat3=NULL,    # num [1:3, 1:80, 1:100]
  mat4=NULL,    # num [1:10, 1:3]
  a=0.025       # scalar
)
   {
  omega = diag(c(1,diag(a * mat3 %*% mat2 %*% t(mat3))))[-1,-1]

  temp = solve(t(mat3) %*% solve(omega) %*% mat3 + solve(a * mat2))

  out = temp %*% (solve(a * mat2) %*% mat1 + t(mat3) %*% solve(omega) %*% mat4)

  return(out)
}

Instead of running:

customfunction(mat1[1,], mat2[,,1], mat3[,,1], mat4[1,])
customfunction(mat1[2,], mat2[,,2], mat3[,,2], mat4[1,])
customfunction(mat1[3,], mat2[,,3], mat3[,,3], mat4[1,])
...
customfunction(mat1[61,], mat2[,,61], mat3[,,61], mat4[2,])
customfunction(mat1[61,], mat2[,,61], mat3[,,61], mat4[2,])
etc...

or

customfunction(mat1[1,], mat2[[1]], mat3[[1]], mat4[1,])
customfunction(mat1[2,], mat2[[2]], mat3[[2]], mat4[1,])
customfunction(mat1[3,], mat2[[3]], mat3[[3]], mat4[1,])
...
customfunction(mat1[61,], mat2[[61]], mat3[[61]], mat4[2,])
customfunction(mat1[61,], mat2[[61]], mat3[[61]], mat4[2,])

Note that mat4[i,] change ever 60th iteration, i.e. I apply it 60 times holding mat4[1,] constant, and then apply with the next 60th iterations with mat[2,]. Is possible to apply (or loop) it such that it will run the function 100 times for each element/row such that it will create a 100x80 matrix? If so, how?

Many thanks!


Solution

  • This is a task for sapply():

    sapply(1:100, function(i) customfunction(mat1[i,], mat2[,,i], mat3[,,i], mat4[1+ (i-1)%/%60,]))
    

     or

    sapply(1:100, function(i) customfunction(mat1[i,], mat2[[i]], mat3[[i]], mat4[1+ (i-1)%/%60,]))