How to apply a function to a multidimensional array based on its indices

I have a 4-dimensional array, and I want to fill the slots with values ​​that are input functions. Thanks to a search on the forums here, I found that the "external" function is useful for 2x2 matrices, but cannot be applied to common multidimensional arrays. Is there anything that can achieve this in R more efficiently than the following code?

K <- array(0,dim=c(2,2,2,2)) #dimensions will be much larger
for(x1 in 1:2)
{
  for(y1 in 1:2)
  {
    for(x2 in 1:2)
    {
      for(y2 in 1:2)
      {
        K[x1,y1,x2,y2] <- x1*y2 - sin(x2*y1) #this is just a dummy function.
      }   
    }
  }
}

Thanks in advance for any help.

+3
source share
1 answer

; , , . , K, . K[] <- , dataframe. LHS K, , , :

dfm <- expand.grid(x1=1:2,x2=1:2,y1=1:2,y2=1:2) 
K[] <- with(dfm, x1*y2 - sin(x2*y1 ) )

: data.frame x1, x2, y1, y2 , : K [cbind (index-vectors)] < - values ​​construction:

mtx<- data.matrix( expand.grid(x1=1:2,x2=1:2,y1=1:2,y2=1:2) )
K[mtx] <- apply(mtx, 1, function(x) x["x1"]*x["y2"] - sin(x['x2']*x['y1']) )
#----------------
> K
, , 1, 1

        [,1]       [,2]
[1,] 0.158529 0.09070257
[2,] 1.158529 1.09070257

, , 2, 1

          [,1]     [,2]
[1,] 0.09070257 1.756802
[2,] 1.09070257 2.756802

, , 1, 2

        [,1]     [,2]
[1,] 1.158529 1.090703
[2,] 3.158529 3.090703

, , 2, 2

        [,1]     [,2]
[1,] 1.090703 2.756802
[2,] 3.090703 4.756802
+3

All Articles