Benjamin Tyner
2007-Jan-16 21:30 UTC
[R] curious about dimension of 'apply' output when MARGIN=1
Reading the documentation for 'apply', I understand the following is working exactly as documented: > M<-matrix(1:6,ncol=2) > M [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 > apply(M,2,function(column) column+c(1,2,3)) [,1] [,2] [1,] 2 5 [2,] 4 7 [3,] 6 9 > apply(M,1,function(row) row+c(1,2)) [,1] [,2] [,3] [1,] 2 3 4 [2,] 6 7 8 I'm not proposing any changes or extra arguments to 'apply'. Rather, I'm wondering what is the benefit for (or rationale behind) this somewhat unintuitive behavior in the case that MARGIN=1. Thanks, Ben
Gabor Grothendieck
2007-Jan-17 00:16 UTC
[R] curious about dimension of 'apply' output when MARGIN=1
The reshape package has an idempotent apply, iapply:> library(reshape) > iapply(M,1,function(row) row+c(1,2))[,1] [,2] [1,] 2 6 [2,] 3 7 [3,] 4 8 On 1/16/07, Benjamin Tyner <btyner at stat.purdue.edu> wrote:> Reading the documentation for 'apply', I understand the following is > working exactly as documented: > > > M<-matrix(1:6,ncol=2) > > M > [,1] [,2] > [1,] 1 4 > [2,] 2 5 > [3,] 3 6 > > apply(M,2,function(column) column+c(1,2,3)) > [,1] [,2] > [1,] 2 5 > [2,] 4 7 > [3,] 6 9 > > apply(M,1,function(row) row+c(1,2)) > [,1] [,2] [,3] > [1,] 2 3 4 > [2,] 6 7 8 > > I'm not proposing any changes or extra arguments to 'apply'. Rather, I'm > wondering what is the benefit for (or rationale behind) this somewhat > unintuitive behavior in the case that MARGIN=1. > > Thanks, > Ben > > ______________________________________________ > R-help at stat.math.ethz.ch 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. >