[R] Using different function (parameters) with apply

Berend Hasselman bhh at xs4all.nl
Thu Apr 18 09:23:27 CEST 2013


On 18-04-2013, at 07:20, Sachinthaka Abeywardana <sachin.abeywardana at gmail.com> wrote:

> Hi All,
> 
> I have the following problem (read the commented bit below):
> 
> a<-matrix(1:9,nrow=3)
> 
> 
> a
> 
>     [,1] [,2] [,3]
> [1,]    1    4    7
> [2,]    2    5    8
> [3,]    3    6    9
> 
> 
> div<-1:3
> 
> apply(a,2,function(x)x/div) ##want to divide each column by div-
> instead each row is divided##
> 
> 
>     [,1] [,2] [,3]
> [1,]    1  4.0    7
> [2,]    1  2.5    4
> [3,]    1  2.0    3
> 

column 1 is c(1,2,3) and divided by your vector div gives the first column c(1/1,2/2,3/3) = c(1,1,1) and that is correct.
column 3 is c(7,8,9) and divided by vector div gives c(7/1, 8/2 , 9/3) = c(7,4,3). Also correct.


> apply(a,1,function(x)x/div) ##Changing Margin from 2 to 1 does
> something completele weird##         [,1]     [,2] [,3]
> [1,] 1.000000 2.000000    3
> [2,] 2.000000 2.500000    3
> [3,] 2.333333 2.666667    3
> 

You are dividing each row by vector div). The result for row 1 is the first column and so forth.
Probably if you did t(…) you would get what you want/expect.

> Any thoughts?
> 

Your conclusions are incorrect.
What is the result that you want (or expect)?

Berend



More information about the R-help mailing list