# [R] Problem using apply

Sarah Goslee sarah.goslee at gmail.com
Tue Jun 1 22:37:05 CEST 2010

```As far as I can tell, your code works perfectly. It's just that the mean of
your rows is the same as the mean of your columns because the matrix
is symmetric.

Compare these two examples (the first one is yours):

> m = matrix( c(1,4,7,4,5,8,7,8,9), nrow = 3 )
> m
[,1] [,2] [,3]
[1,]    1    4    7
[2,]    4    5    8
[3,]    7    8    9
> apply(m, 1, sum)
 12 17 24
> apply(m, 2, sum)
 12 17 24
> apply(m, 1, mean)
 4.000000 5.666667 8.000000
> apply(m, 2, mean)
 4.000000 5.666667 8.000000
>
>
> m <- matrix(1:9, nrow=3)
> apply(m, 1, sum)
 12 15 18
> apply(m, 2, sum)
  6 15 24
> apply(m, 1, mean)
 4 5 6
> apply(m, 2, mean)
 2 5 8
>

Henrique provides methods for doing the same thing
without using apply(), which may be useful if this isn't
a test case for solving a larger problem.

If your problem is something other than that, you'll need to
explain more clearly.

Sarah

On Tue, Jun 1, 2010 at 3:21 PM, Joachim de Lezardiere
<joachim.lezard at gmail.com> wrote:
> Thank you Henrique,
>
>
>
> I still don’t understand why my code doesn’t work ?  According to the
> definition of apply function it should work no ?
>
>
>
> From: Henrique Dallazuanna [mailto:wwwhsd at gmail.com]
> Sent: Tuesday, June 01, 2010 7:34 PM
> To: Joachim de Lezardiere
> Cc: r-help at r-project.org
> Subject: Re: [R] Problem using apply
>
>
>
> The mean by col and by row are the same:
>
> colMeans(m) == rowMeans(m)
>
> So:
>
> m / rowMeans(m) # You don't need apply here
> m / colMeans(m)
>
> On Tue, Jun 1, 2010 at 2:26 PM, Joachim de Lezardiere
> <joachim.lezard at gmail.com> wrote:
>
> Hello ,
>
>
>
> I can not get apply function to do what I want when doing stuff on rows.
> Let's say I want to divide the rows of matrix by their mean, the below show
> you get the same result weather you use 1 or 2, i.e. same result for columns
> than for means..:(
>
>
>
> Thanks a lot for the help,
>
>
>
>
>
>
>
> m = matrix( c(1,4,7,4,5,8,7,8,9), nrow = 3 )
>
>
>
> divideByMean  = function( v ){
>
> return( v/mean(v))
>
> }
>
>
>
> rowMean = c( mean( m[1,]),mean( m[2,]),mean( m[3,]) )
>
> rowMean
>
>
>
> colMean = c( mean( m[,1]),mean( m[,2]),mean( m[,3]) )
>
> colMean
>
>
>
> m
>
> print("ByRow")
>
> apply( m, 1, divideByMean)
>
>
>
> print("ByCol")
>
> apply( m, 2, divideByMean)
>
>
>
>
>
>
>

--
Sarah Goslee
http://www.functionaldiversity.org

```