[Rd] function "apply" and 3D arrays (PR#7221)

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu Sep 9 20:33:17 CEST 2004


jaroslaw.w.tuszynski at saic.com writes:

> Full_Name: jarek tuszynski
> Version: 1.8.1
> OS: windows 2000
> Submission from: (NULL) (198.151.13.10)
> 
> 
> Example code:
> > a=array(1:27, c(3,3,3))
> > apply(a,2, var)
>       [,1] [,2] [,3]
>  [1,]    1    1    1
>  [2,]    1    1    1
>  [3,]    1    1    1
>  [4,]    1    1    1
>  [5,]    1    1    1
>  [6,]    1    1    1
>  [7,]    1    1    1
>  [8,]    1    1    1
>  [9,]    1    1    1
> > apply(a,2, mean)
> [1] 11 14 17
> > apply(a,2, sd)
>      [,1] [,2] [,3]
> [1,]    1    1    1
> [2,]    1    1    1
> [3,]    1    1    1
> 
> I could not figure out from the documentation how MARGIN argument of function
> "apply" works in case of arrays with dimentions larger than 2, so I created the
> above test code. I still do not know how it suppose to work but I should not get
> the results with different dimentions, while calculating var and sd.

All in accordance with documentation, i.e. no bug. The fundamental
issue is that

> mean(a[,3,])
[1] 17
> var(a[,3,])
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1
> sd(a[,3,])
[1] 1 1 1

In particular, var() gives a covariance matrix, but there's no such
thing as an sd() matrix, so you get the columnwise sd().

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907



More information about the R-devel mailing list