Reputation: 333
Related to this question: Multiply multidimensional array with same-sized matrix
If I create the following array and matrix:
a <- array(1, dim=c(2,2,3))
b <- matrix(c(1,1,1,1), nrow=2)
and would like to carray out an elementwise multiplication of b
with each slice of a
moving along the 3rd dimension, I would use apply
. However, I get the following strange result:
> dim(apply(a, 3, `*`, b))
[1] 4 3
> newa <- array(0, dim=c(2,2,3))
> newa[] <- apply(a, 3, `*`, b)
> dim(newa)
[1] 2 2 3
Why do these two things give different answers?
Upvotes: 2
Views: 639
Reputation: 7455
The resulting dimension of apply(a, 3,
*, b)
is 4 3
because according to the documentation, see ?apply
:
If each call to
FUN
returns a vector of lengthn
, thenapply
returns an array of dimensionc(n, dim(X)[MARGIN])
ifn > 1
.
In this case, each call to FUN
returns a vector of length 4
and the dimension with MARGIN=3
is 3
. Note that the results of each call of FUN
in apply
is coerced to a vector
not a matrix
.
Now, with newa[] <- array(...
, you are replacing the values in the newa
object with the values from the array
computation. The attributes of newa
is not changed, so its dimensions is still 2 2 3
.
Hope this helps.
Upvotes: 2