[R] Element-by-element division

peter dalgaard pdalgd at gmail.com
Wed Jul 29 11:30:06 CEST 2015


> On 28 Jul 2015, at 15:53 , Sarah Goslee <sarah.goslee at gmail.com> wrote:
> 
> Sure, there are lots of ways to do everything in R. But mixing in
> apply muddles the issue, since apply() and sweep() use different logic
> to determine MARGIN.

Actually, apply() and sweep() were designed together and use exactly the SAME logic to determine the margin. E.g., to sweep out means according to the last two dimensions of an array, you do

> m <- array(1:24, c(4,3,2))
> (mm <- apply(m, c(2,3), mean))
     [,1] [,2]
[1,]  2.5 14.5
[2,]  6.5 18.5
[3,] 10.5 22.5
> sweep(m, c(2,3), mm, "-")
, , 1

     [,1] [,2] [,3]
[1,] -1.5 -1.5 -1.5
[2,] -0.5 -0.5 -0.5
[3,]  0.5  0.5  0.5
[4,]  1.5  1.5  1.5

, , 2

     [,1] [,2] [,3]
[1,] -1.5 -1.5 -1.5
[2,] -0.5 -0.5 -0.5
[3,]  0.5  0.5  0.5
[4,]  1.5  1.5  1.5


The trouble comes when people miss the point and start using apply() in ways it wasn't designed for... 

-pd

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list