[R] A primitive OO in R -- where next?

Don MacQueen macq at llnl.gov
Thu May 13 17:22:39 CEST 2010

This is not really OO at all, in my opinion. It's an example of the 
amazing flexibility of the language.

I'd like to add on to what Erik said, with an example:

>  sum(1:10)
[1] 55

>  foo <- sum
>  foo(1:10)
[1] 55

>  junk <- list(a=sum)
>  junk$a(1:10)
[1] 55

sum is an R object; it happens to be a function.

When I do
   foo <- sum
I'm creating another R object. It's also a function, so I use it with 
the same syntax.

When I do
    junk <- list(a=sum)
I'm creating another R object. It's a list, and its first element, 
named 'a', is a function.
Since the element is a function, I use it just like any other 
function, i.e, follow its name with a pair of parentheses with 
arguments between them.

Note that in the last example it doesn't matter what the other 
elements in the list, if any, are. I could just as well do
   junk <- list( foo=data.frame(x=1:4), b=c('x','y'), dd=sum)
   junk$dd( junk$foo$x )
are valid statements. There's no connection between using 'junk' both 
inside the parentheses and outside. Since junk$dd is a function, you 
can supply it with any R object, and it doesn't matter where that R 
object comes from.

I doubt that it's documented in the way you might be expecting. It's 
a result of the generality of list elements -- they can be any R 

Hope this helps.

At 10:48 PM +0100 5/12/10, Ted Harding wrote:
>Greetings All,
>Out of curiosity, I've just done a very primitive experiment:
>   Obj <- list(Fun=sum, Dat=c(1,2,3,4))
>   Obj$Fun(Obj$Dat)
>   # [1] 10
>That sort of thing (much more sophisticated) must be documented
>mind-blowingly somewhere. Where?
>Where I stand right now: The above (and its immediately obvious
>generalisations, like Obj$Fun<-cos) is all I know about it so far.
>E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
>Fax-to-email: +44 (0)870 094 0861
>Date: 12-May-10                                       Time: 22:48:14
>------------------------------ XFMail ------------------------------
>R-help at r-project.org mailing list
>PLEASE do read the posting guide http://*www.*R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA

More information about the R-help mailing list