nous.calc
nous.calc

Reputation: 25

R: Multiplication of two arrays of different size

I want to multiply two arrays, A and B. (only code shown due to size)

a <- array(c(1:72), dim=c(18,4))
dimnames(a) = list(c(1:18),
                   c("ALPHA", "BETA", "GAMMA", "DELTA"))

b <- array(c(1:360), dim=c(5,4,18)) 
dimnames(b) = list(c("ONE", "TWO" ,"THREE", "FOUR", "FIVE"),
                   c("ALPHA", "BETA", "GAMMA", "DELTA"),
                   c(1:18))

I want to multiply the first table of array B by the row 1 of table A, the second table of array B by row 2 of array A and so on. I just can not figure out how ot do this while doing the multiplication in a way that also the columns fit together (e.g. ALPHA:ALPHA, BETA:BETA, and so on...)

By using sweep, I get 18 tables but the tables are not multiplied by column. Instead, it seems that columns are multiplied by rows. (Table 1/18) is shown below as result.

sweep(b, MARGIN=2, a, "*")


      ALPHA BETA GAMMA DELTA
ONE       1   12    33    64
TWO      10   42    84   136
THREE    27   80   143   216
FOUR     52  126   210   304
FIVE     85  180   285   400

Instead, I need this (also only the first table shown):

        ALPHA  BETA  GAMMA DELTA
ONE       1*1  6*19  11*37 16
TWO       2*1  7*19  12*37 17
THREE     3*1  8*19  13*37 18
FOUR      4*1  9*19  14*37 19
FIVE      5*1  10*19 15*37 20

Upvotes: 0

Views: 1184

Answers (1)

Bambs
Bambs

Reputation: 567

Would something like this do the trick ?

number=dim(a)[1]    
lapply(1:number,function(x){t(apply(b[,,x],1,function(z){z*a[x,]}))})

    [[1]]
          ALPHA BETA GAMMA DELTA
    ONE       1  114   407   880
    TWO       2  133   444   935
    THREE     3  152   481   990
    FOUR      4  171   518  1045
    FIVE      5  190   555  1100

Upvotes: 1

Related Questions