[Rd] as.function()

Robin Hankin r.hankin at noc.soton.ac.uk
Mon Jan 14 12:59:58 CET 2008


On 14 Jan 2008, at 11:50, Duncan Murdoch wrote:

> Robin Hankin wrote:
>> Hi
>>

[snip]

>> a <- crossprod(matrix(rnorm(12),ncol=3))
>> class(a) <- "foo"
>>
>> f <- as.function(a)       # need help to write as.function.foo()
>> x <- diag(3)
>>
>> f(x)             #should give tr(ax)
>>
>> a <- 4
>> f(x)           # should still give tr(ax) even though "a" has been   
>> reassigned.
>>
>>
> Brian's answer was what you want.  A less general version is this:
>
> > as.function.foo <- function(x, ...) {
> +    function(b) tr(x %*% b)
> + }
>


Wow.  Got it!  Looks like I'll have to read the R Language Definition  
again.

Thanks everyone.




> (I switched the names of the args, because the first arg to  
> as.function.foo should match the name of the first arg to  
> as.function).
>
> I was a little surprised that this worked even if a was changed  
> without ever evaluating f, because I thought lazy evaluation would  
> mess up that case.  But of course the value of x is forced when R  
> evaluates it to find out the class for dispatch to the method.
>
> Duncan Murdoch

--
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-devel mailing list