2

Apparently this question has been asked before here, thanks for the quick answer!

The following issue has been puzzling me lately and I hope someone can help me with this. When using apply, the dimensions of my matrix end up being switched. See example below:

> A = matrix(c(2, 4, 3, 1, 5, 7), nrow=2, ncol=3, byrow = TRUE)
> A
     [,1] [,2] [,3]
[1,]    2    4    3
[2,]    1    5    7

> M = c(1, 2, 3)

> B = apply(A, 1, "*", M)
> B
     [,1] [,2]
[1,]    2    1
[2,]    8   10
[3,]    9   21

I know this can easily be transposed, so that isn't the problem. But my question is, why does R do this?

Hope you can help me with this.

Community
  • 1
  • 1
  • We can just do `A*M[col(A)]` without the `apply` – akrun Jan 21 '16 at 13:54
  • See also [Results transposed with R apply](http://stackoverflow.com/questions/18312389/results-transposed-with-r-apply/18312548#18312548) or [R: rownames, colnames, dimnames and names in apply](http://stackoverflow.com/questions/15229199/r-rownames-colnames-dimnames-and-names-in-apply). – Henrik Jan 21 '16 at 14:09

1 Answers1

1

The elements of a matrix are stored in RAM: 1. elements of the first column, 2. elements of the second column, ... and so on. So, when apply() builds the resulting object the first elements are the elements of the first column ... and so on.
(In memory the position of the elements of a matrix is FORTRAN-like.)

jogo
  • 12,469
  • 11
  • 37
  • 42