Search code examples
rfunctionreference-class

How to subclass a function in R?


I was wondering if it is possible to use Reference Classes to subclass a function in R. For instance, the following

> CustomFunction <- setRefClass("CustomFunction", contains = "function")
> foo <- CustomFunction()
> foo()
NULL

works OK (does not throw an error), but how can I customise the behaviour (i.e. other than returning NULL)? How can I define function arguments?

I also tried

> setMethod("(",
>   signature(x = "CustomFunction"),
>   function(...) {
>       "Hello!"    # A function that always returns "Hello!"
>   }
> )
Error in genericForPrimitive(f) : 
  methods may not be defined for primitive function ‘(’ in this version of R

but that doesn't seem to work.


I was hoping that being able to subclass functions means that I could implement custom behaviour before and after function calls. E.g. to have functions that automatically logs the call expression each time it is called (for audit purposes), or to create functions that automatically throws an error if NULL is returned etc etc.


Solution

  • You don't need Reference Classes for this, you can just enclose the function of interest

    logger <- function(f) {
        force(f)
        function(...) {
            print("running function...")
            f(...)
        }
    }
    
    printhello <- function(name="Al") print(paste("hello", name))
    
    printhello_logged <- logger(printhello)
    
    printhello()
    # [1] "hello Al"
    printhello_logged("Zed")
    # [1] "running function..."
    # [1] "hello Zed"
    

    If this is for auditing/testing type purposes, you might be interested in trace() which allows you to attach code to various parts of functions.