2

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?

1 Answer 1

2

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 length n, then apply returns an array of dimension c(n, dim(X)[MARGIN]) if n > 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.