[R] sweep() and recycling
    Robin Hankin 
    r.hankin at noc.soton.ac.uk
       
    Mon Jun 20 11:32:44 CEST 2005
    
    
  
Hi
I had a hard-to-find bug in some of my code the other day, which I 
eventually
traced to my misusing of sweep().
I would expect sweep() to give
me a warning if the elements don't recycle nicely, but
  X <- matrix(1:36,6,6)
  sweep(X,1,1:5,"+")
      [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    2    9   16   23   30   32
[2,]    4   11   18   25   27   34
[3,]    6   13   20   22   29   36
[4,]    8   15   17   24   31   38
[5,]   10   12   19   26   33   40
[6,]    7   14   21   28   35   37
gives no warning, even though (5,36)=1.
Also,
sweep(X,1,c(1,1000),"+")
and
sweep(X,2,c(1,1000),"+")
behave as expected,   But
sweep(X,1,1:5,"+")
and
  sweep(X,2,1:5,"+")
are identical!
I find this confusing, because I interpret sweep()'s second
argument as the margin along which the third argument is fourth 
argumented
this interpretation breaks down in a non-obvious way if elements
are left over after recycling.
If sweep() had given a warning, I would have found my mistake much 
faster.
Could we  make sweep() issue a warning
under these circumstances or, failing that, add a warning to sweep.Rd 
saying
that no warning is given in cases like this?
--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743
    
    
More information about the R-help
mailing list