Another alternative is to use the underappreciated function
'sweep()':
sweep(A, 1:2, a, "+")
Internally this is about the same as your 'A + array(a, c(2,2,2))'.
But it has the advantage that it makes explicit what the
relationship between the dimensions of 'A' and 'a' is. I find
that relying on implicit recycling tends to produce errors that
are hard to trace, and code that is hard to understand six months
later.
Rich Raubertas
Merck & Co.
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Prof
> Brian Ripley
> Sent: Wednesday, March 31, 2004 10:00 AM
> To: Tamas Papp
> Cc: R-help mailing list
> Subject: Re: [R] array addition doesn't recycle!
>
>
> The recycling rules are documented and this is not amongst them.
> Computer packages do have a tendency to follow their rules
> rather than
> read your mind.
>
> I suspect A + as.vector(a) is what you intended.
>
> On Wed, 31 Mar 2004, Tamas Papp wrote:
>
> > Hi,
> >
> > I have noticed the following:
> >
> > > a <- array(1:4, c(2, 2))
> > > A <- array(1:4, c(2,2,2))
> > > A + a
> > Error in A + a : non-conformable arrays
> >
> > It works with a matrix + a vector, why doesn't it work with
arrays?
> > Am I missing something?
> >
> > How would you do the above operation efficiently (ie I need to add a
> > matrix to each "plane" of 3-dim array)? At the moment I am
using
> > something like
> >
> > A + array(a, c(2,2,2))
> >
> > but it doesn't seem that efficient.
>
> Why do you think is `not that efficient'? Does you have a
> need to save
> microseconds?
>
> --
> Brian D. Ripley, ripley at stats.ox.ac.uk
> Professor of Applied Statistics, stats.ox.ac.uk/~ripley
> University of Oxford, Tel: +44 1865 272861 (self)
> 1 South Parks Road, +44 1865 272866 (PA)
> Oxford OX1 3TG, UK Fax: +44 1865 272595
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> R-project.org/posting-guide.html
>
>