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

From: Liaw, Andy <andy_liaw_at_merck.com>
Date: Fri 10 Sep 2004 - 04:22:38 EST


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@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@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>



R-devel@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Fri Sep 10 04:30:45 2004

This archive was generated by hypermail 2.1.8 : Wed 03 Nov 2004 - 22:45:14 EST