# [R] Behavior of apply()

Marc Schwartz marc_schwartz at me.com
Thu Dec 8 22:40:10 CET 2011

```On Dec 8, 2011, at 3:30 PM, Doran, Harold wrote:

> Suppose I have the following matrix
>
>> class(cov_50)
> [1] "matrix"
>> cov_50
>          [,1]     [,2]
> [1,] 0.3201992 2.308084
> [2,] 6.7312928 5.719641
>
> I then use the following function via apply and get the desired output, a list
>
> signif <- function(x) which(abs(x) > 1.96)
> apply(cov_50, 1, signif)
>
>> apply(cov_50, 1, signif)
> [[1]]
> [1] 2
>
> [[2]]
> [1] 1 2
>
> However, I can't see why the following occurs
>
>> class(cov_25)
> [1] "matrix"
>> cov_25
>          [,1]     [,2]
> [1,] 12.116106 14.81248
> [2,]  5.492176  4.73138
>
>> apply(cov_25, 1, signif)
>     [,1] [,2]
> [1,]    1    1
> [2,]    2    2
>
> So, using the same function (signif) on a different object of the same class yields a matrix and *not* a list as desired.
>
> I can't see any reason for the different output.

Harold,

Per the Value section of ?apply:

If the calls to FUN return vectors of different lengths, apply returns a list of length prod(dim(X)[MARGIN]) with dim set to MARGIN if this has length greater than one.

In your first example, the first row only has one value that is returned by signif() and then second row has two. So a list is returned.

In your second example, both rows have two values that are returned by signif(), thus a matrix can be returned.

The key is not that the two objects are both matrices, but that there are differing lengths in the returned values from the rows in each.

HTH,

Marc Schwartz

```