[R] apply on rows and columns?
Sarah Goslee
sarah.goslee at gmail.com
Wed Nov 16 21:18:53 CET 2011
Hi,
On Wed, Nov 16, 2011 at 3:13 PM, <rkevinburton at charter.net> wrote:
>
> I have the following scenario:
>
>> m <- matrix(1:4, ncol=2)
>> m
> [,1] [,2]
> [1,] 1 3
> [2,] 2 4
>> apply(m, 2, sum)
> [1] 3 7
>> apply(m, 1, sum)
> [1] 4 6
>
> So I can apply to rows *or* columns. According to the documentation
> (?apply)
>
> MARGIN a vector giving the subscripts which the function will be applied
> over. E.g., for a matrix 1 indicates rows, 2 indicates columns, c(1, 2)
> indicates rows and columns. Where X has named dimnames, it can be a
> character vector selecting dimension names.
>
>
> But I get the following results:
>
>> apply(m, c(1,2), sum)
> [,1] [,2]
> [1,] 1 3
> [2,] 2 4
>
> How am I to interpret this result?
I'm pretty sure R is taking the sum of m[1,1] and putting it [1,1],
and the sum of m[1,2] and putting it in [1,2] and so on. You
instructed apply() to work on rows and columns *simultaneously*,
rather than sequentially.
apply() on c(1,2) is useful if you have a matrix that's three-dimensional,
but not so much if it's two dimensional.
What are you trying to accomplish?
Sarah
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list