[Rd] function "apply" and 3D arrays (PR#7221)
Tony Plate
tplate at blackmesacapital.com
Thu Sep 9 20:29:53 CEST 2004
[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 at 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 at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-devel
More information about the R-devel
mailing list