[R] difference between the meaning of MARGIN in sweep() and apply()

Charles C. Berry cberry at tajo.ucsd.edu
Wed Dec 16 19:04:59 CET 2009


On Wed, 16 Dec 2009, Levi Waldron wrote:

> For example, subtracting 1:2 from the rows of a two-column matrix:
>
>> t(apply(matrix(1:6,ncol=2),MARGIN=1,function(y) y - 1:2))
>     [,1] [,2]
> [1,]    0    2
> [2,]    1    3
> [3,]    2    4
>> sweep(matrix(1:6,ncol=2),MARGIN=2,1:2,FUN="-")
>     [,1] [,2]
> [1,]    0    2
> [2,]    1    3
> [3,]    2    4
>
> Is there a logic to this difference, or is it just a quirk of the history of
> these functions?

Well

 	sweep(mat,MARGIN, apply(mat,MARGIN, applyfun), sweepfun)

does it for me.

> mat <- matrix(1:6,ncol=2)
> sweep( mat, 2, apply(mat, 2, mean),'-')
      [,1] [,2]
[1,]   -1   -1
[2,]    0    0
[3,]    1    1
>

Chuck

>
> I found one discussion on this topic, but without what I thought was a very
> conclusive end:
>
> http://finzi.psych.upenn.edu/Rhelp08/2009-March/191930.html
>
>
> -- 
> Levi Waldron
> post-doctoral fellow
> Jurisica Lab, Ontario Cancer Institute
> Division of Signaling Biology
> TMDT 9-304D
> 101 College Street
> Toronto, Ontario M5G 1L7
> (416)581-7453
>
> 	[[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.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901




More information about the R-help mailing list