[R] list arithmetic

Bill Venables Bill.Venables at cmis.csiro.au
Tue Apr 18 16:03:34 CEST 2000


At 03:24 PM 18/4/2000 +0200, Trenkler, Dietrich wrote:
>I'm an old APL fossil and I got  used to work with nested arrays there.
>In APL(2) you can write 1+(1 2 3)(4 5 6 7 8 9) and get (2 3 4)(5 6 7 8 9
>10).
>A similar concept is R's lists. So it takes me by surprise to learn that
>
>        1+list(1:3,4:9)
>
>delivers an
>Error in 1 + list(1:3, 4:9) : non-numeric argument to binary operator
>Is there any particular reason why this doesn't work as expected? 

Not too many others would expect it, I suppose.  I can only guess, but my
surmise is that lists are considered composite objects with no particular
reason to have numeric components at all (and usually will not) so
arithmetic on lists is not a very natural sort of operation to want to do.

>I know that 
>
>           lapply(list(1:3,4:9),"+",y=1)
>
>is an alternative but I hold that 1+list(1:3,4:9) looks more
>straightforward.

Hmm.

If you were willing to construct a class of objects, say "numericList",
that had a list as the prototype, you could have objects that behaved as
lists when you needed them to, but you could also write a group generic
method for them that would allow arithmetic operations in the kind of way
you see as natural.  For example, data frames are lists with class
data.frame and methods exist to allow them to be used very much like
matrices.  The same sort of trick can be used for your purpose.  (The
details are suppressed for brevity, but they are pretty simple.)

Bill Venables.

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list