1

I am trying to divide each row of my matrix by the sum of that same row:

a <- matrix(1:25,nrow=5,ncol=5)
a <- apply(a,1,function(x) x/sum(x))

this gives the intended result but it is structured in columns as opposed to rows:

           [,1]       [,2]       [,3]       [,4]       [,5]
[1,] 0.01818182 0.03333333 0.04615385 0.05714286 0.06666667
[2,] 0.10909091 0.11666667 0.12307692 0.12857143 0.13333333
[3,] 0.20000000 0.20000000 0.20000000 0.20000000 0.20000000
[4,] 0.29090909 0.28333333 0.27692308 0.27142857 0.26666667
[5,] 0.38181818 0.36666667 0.35384615 0.34285714 0.33333333
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
Imlerith
  • 479
  • 1
  • 7
  • 15
  • didn't know that, i've just looked up ?matrix, do you think if I put byrow=TRUE, it would fix the problem ? – Imlerith Jun 30 '16 at 18:46
  • There is nothing called `col`. Please change that to `ncol` and for your desired result add `byrow =TRUE` – user2100721 Jun 30 '16 at 18:46

2 Answers2

4

Because the matrix is structured by columns, dividing the matrix by the row sums gives the correct result:

> a / rowSums(a)
           [,1]      [,2] [,3]      [,4]      [,5]
[1,] 0.01818182 0.1090909  0.2 0.2909091 0.3818182
[2,] 0.03333333 0.1166667  0.2 0.2833333 0.3666667
[3,] 0.04615385 0.1230769  0.2 0.2769231 0.3538462
[4,] 0.05714286 0.1285714  0.2 0.2714286 0.3428571
[5,] 0.06666667 0.1333333  0.2 0.2666667 0.3333333

This works because the vector returned by rowSums is recycled.

For the apply to work, you would simply need to transpose the result, as the return value of apply is built up by column, not row.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
  • so "a / rowSums(a)" divides rows of "a" by their respective sums is that the default way? what if you wanted to divide columns of "a" by rowSums ? – Imlerith Jun 30 '16 at 18:55
  • Say you wanted to divide each column by its sum, then you could use `apply` as you have done, or perhaps `a / rep(colSums(a), each=nrow(a))`. Same for dividing each column by the row sum (for a square matrix). – Matthew Lundberg Jun 30 '16 at 18:58
0

That's the way apply is supposed to work. By default, matrices are filled by column in R. Note the documentation for ?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.

gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79