R apply when arguments contain arrays and scalars

I want to avoid the next cycle:

for(i in 1:2){
vectVal[i] = myFunc(M[,,i],S[,,i],phi2, sig2)
}

using apply .

The problem is that the arguments passed to the apply function contain arrays (-> M and S) and scalars (-> phi2 and sig2).

I tried the following:

apply(M,3,myFunc, S = S, phi2 = phi2, sig2 = sig2)

resulting in an error message, since S is an array, not a matrix, as required in myFunc (see below):

Here is the reproducible code:

M = array(data = c(
  0.5, 0.7, 0.45,
  0.5, 0.3, 0.45,
  0.5, 0.7, 0.3,
  0.5, 0.3, 0.7,
  0.5, 0.7, 0.45,
  0.5, 0.3, 0.55),
  dim = c(3,2,2),
)

S = array(data = c(
   0.7723229, -0.2149794, -0.2159068,
  -0.2149794,  0.7723229, -0.2083123,
  -0.2159068, -0.2083123,  0.7723229,
   0.7723229, -0.2149794, -0.2149794,
  -0.2149794,  0.7723229, -0.1783025,
  -0.2149794, -0.1783025,  0.7723229,
   0.7723229, -0.2149794, -0.2176665,
  -0.2149794,  0.7723229, -0.2111496,
  -0.2176665, -0.2111496,  0.7723229),
   dim = c(3,3,2)
)

phi2 = 0.5
sig2 = 0.3

myFunc = function(M, S, phi2, sig2){
  valMult = M[,1]%*%diag(S)
  valEnd = valMult + phi2 - sig2
return(valEnd)
}

vectVal = vector(length = 2)

for(i in 1:2){
  vectVal[i] = myFunc(M[,,i],S[,,i],phi2, sig2)
}

vectVal

Does anyone have any ideas?

+4
source share
1 answer

( ) plyr lists ( ). mapply :

require( plyr)
ml <- alply( M , 3 )
sl <- alply( S , 3 )
mapply( myFunc , ml , sl , phi2 , sig2 )
#       1        2 
#1.474333 1.358484 

:

( , for %*% [. @JorisMeys ]) , diag of S, colSums :

s <- apply(S,3,diag)
colSums( M[,1,] * s ) + phi2 - sig2
# [1] 1.474333 1.358484

, :

@JorisMeys . .

+3

All Articles