[Rd] function "apply" and 3D arrays (PR#7221)
Liaw, Andy
andy_liaw at merck.com
Thu Sep 9 20:22:38 CEST 2004
The `problem', I think, is your expectation that the output of apply(a, 2,
var) to be of the same dimension as apply(a, 2, sd) if a has dimensions > 2.
Note that:
> sd(matrix(1:9, 3, 3))
[1] 1 1 1
> var(matrix(1:9, 3, 3))
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
[3,] 1 1 1
because var(), when given a matrix, returns the variance-covariance matrix
of the columns.
The output of sd() can be a bit surprising:
> sd(array(1:27, rep(3, 3)))
[1] 7.937254
This is because sd() looks like:
> sd
function (x, na.rm = FALSE)
{
if (is.matrix(x))
apply(x, 2, sd, na.rm = na.rm)
else if (is.vector(x))
sqrt(var(x, na.rm = na.rm))
else if (is.data.frame(x))
sapply(x, sd, na.rm = na.rm)
else sqrt(var(as.vector(x), na.rm = na.rm))
}
So for matrices and data frames, sd() returns the column standard
deviations. Otherwise it treats the input as a vector and compute the SD.
Andy
> From: jaroslaw.w.tuszynski at saic.com
>
> 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