[R] apply() function: margin argument: "2L" versus "2"

R. Michael Weylandt michael.weylandt at gmail.com
Sat Jun 23 01:00:59 CEST 2012


On Fri, Jun 22, 2012 at 5:53 PM, Rui Barradas <ruipbarradas at sapo.pt> wrote:
> Hello,
>
> 2L is an integer, 2 might be or not. In the case of apply(), there is no
> difference.
>
> All possible values for margin? Any possible(*) combination of the
> dimensions of 'x' in
>
> apply(x, margin, function)
>
> (*) non-null. If, say, x <- array(0, dim=c(2,3,4)) (3dim) then you can call
> any of
>
> apply(x, 1, fun) or apply(x, 2, fun) or apply(x, 3, fun) but not margin=4;
> apply(x, 1:2, fun) or apply(x, c(1, 3), fun) or ...
> apply(x, 1:3, fun)

You can also get away with negative indexing in apply():

x <- array(1:24, dim = c(2,3,4))

apply(x, -1, sum)
apply(x, -c(1,3), sum)

but you seem to loose the array structure.

As usual, you can't mix

apply(x, c(-1, 2), sum) # ERROR

It also seems zero doesn't work here:

apply(x, 0, sum) # ERROR

Best,
Michael

>
> Hope this helps,
>
> Rui Barradas
>
> Em 22-06-2012 23:23, Luba G escreveu:
>
>> What is the difference of using 2L versus 2 as the margin argument in the
>> apply() function? Where can I find detailed information on all of the
>> possible margin arguments?
>>
>>> x
>>
>>      [,1] [,2]
>> [1,]    1    2
>> [2,]    3    4
>> [3,]    5    6
>> [4,]    7    8
>> [5,]    9   10
>>>
>>> sqrt(apply(x, *2L*, function(r.st) var(r.st[!is.na(r.st)])))
>>
>> [1] 3.162278 3.162278
>>>
>>> sqrt(apply(x,* 2*, function(r.st) var(r.st[!is.na(r.st)])))
>>
>> [1] 3.162278 3.162278
>>
>>        [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list