From ripley at stats.ox.ac.uk  Mon Jan 14 13:04:25 2008
From: ripley at stats.ox.ac.uk (Prof Brian Ripley)
Date: Mon, 14 Jan 2008 12:04:25 +0000 (GMT)
Subject: [Rd] as.function()
In-Reply-To: <478B4C88.6070205@stats.uwo.ca>
References: <39993FF2-8FE4-4FB9-A752-8A3ABAB18CEF@noc.soton.ac.uk>
	<478B4C88.6070205@stats.uwo.ca>
Message-ID: <Pine.LNX.4.64.0801141200060.21774@gannet.stats.ox.ac.uk>

On Mon, 14 Jan 2008, Duncan Murdoch wrote:

> Robin Hankin wrote:
>> Hi
>>
>> [this after some considerable thought as to R-help vs R-devel]
>>
>>
>>
>> I want to write a (S3) method for as.function();
>> toy example follows.
>>
>> Given a matrix "a", I need to evaluate trace(ax) as a function of
>> (matrix) "x".
>>
>> Here's a trace function:
>>
>> tr <-  function (a)  {
>>      i <- seq_len(nrow(a))
>>      return(sum(a[cbind(i, i)]))
>> }
>>
>>
>> How do I accomplish the following:
>>
>>
>> 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)
> + }

And see the R version of as.function.polynomial called Rpoly in 'S 
Programming' p.95 for a similar example, in case yet another is needed 
(and to set the record straight after RH's unthinking reply).

> (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

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.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



[Rd] as.function()
Prof Brian Ripley