[R] array addition doesn't recycle!

Robin Hankin rksh at soc.soton.ac.uk
Thu Apr 1 11:20:04 CEST 2004


At 01:39 pm -0500 31/03/04, Raubertas, Richard wrote:
>Another alternative is to use the underappreciated function
>'sweep()':
>
>sweep(A, 1:2, a, "+")
>

I find the following helpful (it's not due to me but I cannot find 
the original poster):


>  "%.+%" <- function(a,x){sweep(a , 2:1 , x ,"+" )}
>  "%+.%" <- function(a,x){sweep(a , 1:2 , x ,"+" )}

>  A <- matrix(1:16,4,4)
>  x <- 10^(0:3)

>  A %+.% x
      [,1] [,2] [,3] [,4]
[1,]    2    6   10   14
[2,]   12   16   20   24
[3,]  103  107  111  115
[4,] 1004 1008 1012 1016
>  A %.+% x
      [,1] [,2] [,3] [,4]
[1,]    2   15  109 1013
[2,]    3   16  110 1014
[3,]    4   17  111 1015
[4,]    5   18  112 1016
>


For 3d arrays this generalizes to

  "%+..%" <- function(a,x){sweep(a , 1 , x ,"+" )}
  "%.+.%" <- function(a,x){sweep(a , 2 , x ,"+" )}
  "%..+%" <- function(a,x){sweep(a , 3 , x ,"+" )}

Then if A <- array(1:8,rep(2,3)) and x <- c(10,100)

A %+..% x et seq give you a consistent method for addition.


-- 
Robin Hankin
Uncertainty Analyst
Southampton Oceanography Centre
SO14 3ZH
tel +44(0)23-8059-7743
initialDOTsurname at soc.soton.ac.uk (edit in obvious way; spam precaution)




More information about the R-help mailing list