[R] array addition

Robin Hankin r.hankin at noc.soton.ac.uk
Wed Dec 19 10:26:44 CET 2007


Hi

suppose I have two arrays x1,x2 of dimensions a1,b1,c1 and
a2,b2,c2 respectively.

I want  x = x1   "+"   x2 with dimensions c(max(a1,a2), max(b1,b2),max 
(c1,c2))

with

x[a,b,c] = x1[a1,b1,c1] + x2[a2,b2,c2] if    a <=min(a1,a2) , b<=min 
(b1,b2), c<=min(c1,c2)

and the other bits either x1 or x2 or zero according to whether the  
coordinates
are "in range" for x1 or x2 or neither.

The answer has to work for arbitrary-dimensioned arrays.

toy example follows (matrices):


 > x1
      [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10
 > x2
      [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
 > x
      [,1] [,2] [,3] [,4] [,5]
[1,]    2    7   12    7    9
[2,]    4    9   14    8   10
[3,]    3    6    9    0    0
 >


Note the zeros at lower-right.


Is there a ready-made solution to this?





--
Robin Hankin
Uncertainty Analyst and Neutral Theorist,
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743



More information about the R-help mailing list