From tplate at blackmesacapital.com  Thu Sep  9 20:29:53 2004
From: tplate at blackmesacapital.com (Tony Plate)
Date: Thu Sep  9 20:30:19 2004
Subject: [Rd] function "apply" and 3D arrays (PR#7221)
In-Reply-To: <20040909180132.7977A10460@slim.kubism.ku.dk>
References: <20040909180132.7977A10460@slim.kubism.ku.dk>
Message-ID: <6.1.0.6.2.20040909121949.05a35db8@mailhost.blackmesacapital.com>

[This appears to have been misposted to r-bugs -- there is no bug reported 
here.]

It's easiest to explore the behavior of high-d apply when your test array 
has different extents on each dimension.  That way you can easily see 
what's happening with each dimension.  Also, when experimenting, use 
FUN=function(x) browser() to see what is getting passed to FUN.

The way I remember what apply() does is that the MAR= argument specifies 
the dimensions to be kept in the result.  Iin apply(x, MAR, FUN), FUN gets 
passed an object with dimensions dim(x)[-MAR].  So, in your example, FUN is 
getting passed a matrix.  The reason you get differently shaped results 
with mean, sd, and var is that each of these gives a differently shaped 
result (scalar, vector, and matrix) when given a matrix.

 > a <- array(1:24, c(2,3,4))
 > apply(a, 2, function(x) browser())
Called from: FUN(array(newX[, i], d.call, dn.call), ...)
Browse[1]> dim(x)
[1] 2 4
Browse[1]> x
      [,1] [,2] [,3] [,4]
[1,]    1    7   13   19
[2,]    2    8   14   20
Browse[1]> mean(x)
[1] 10.5
Browse[1]> sd(x)
[1] 0.7071068 0.7071068 0.7071068 0.7071068
Browse[1]> var(x)
      [,1] [,2] [,3] [,4]
[1,]  0.5  0.5  0.5  0.5
[2,]  0.5  0.5  0.5  0.5
[3,]  0.5  0.5  0.5  0.5
[4,]  0.5  0.5  0.5  0.5

hope this helps,

Tony Plate

At Thursday 12:01 PM 9/9/2004, jaroslaw.w.tuszynski@saic.com wrote:
>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.
>
>Hope this helps,
>
>Jarek
>
>______________________________________________
>R-devel@stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-devel


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