[R] Programming tip: Operators "+.", ".+"

(Ted Harding) Ted.Harding at nessie.mcc.ac.uk
Wed Jul 9 01:49:36 CEST 2003


Since I have devised the following, they may be thought useful
for that secret crock of gold at the end of the rainbow (WHERE
is it??) full of people's programming tips.

  "%+.%"<-function(X,x){sweep(X,1,x,"+")}

  "%.+%"<-function(X,x){sweep(X,2,x,"+")}

  X %+.% x adds a vector x to each of the columns of the matrix X
           with x recycled down columns if length(x) != nrow(X)

  X %+.% x adds a vector x to each of the rows of the matrix X
           with x recycled along rows if length(x) != ncol(X)

Although "X+x" will work down columns, and "t(t(X)+x)" will work
along rows, it is handy to have a consistent (and mnemonic) notation;
and, in any case, neither of these will work if x is a kx1 or 1xk
matrix rather than a vector or a list c(x1,...,xk). The above will
work in all cases, and also X%+.%x = X%+.%t(x), X%.+%x = X%.+%t(x).

Example:
  > S
       [,1] [,2] [,3]
  [1,]  1.0  0.6  0.3
  [2,]  0.6  1.0  0.6
  [3,]  0.3  0.6  1.0
  > x
  [1] 0 1 2
  > S%+.%x
       [,1] [,2] [,3]
  [1,]  1.0  0.6  0.3
  [2,]  1.6  2.0  1.6
  [3,]  2.3  2.6  3.0
  > S%.+%x
       [,1] [,2] [,3]
  [1,]  1.0  1.6  2.3
  [2,]  0.6  2.0  2.6
  [3,]  0.3  1.6  3.0

Anyway,crock of gold or not, somebody may find them useful.
Best wishes to all,
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 167 1972
Date: 09-Jul-03                                       Time: 00:49:36
------------------------------ XFMail ------------------------------




More information about the R-help mailing list