[Rd] as.function()

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


On 14 Jan 2008, at 10:57, Prof Brian Ripley wrote:

> On Mon, 14 Jan 2008, Henrique Dallazuanna wrote:
>
>> Try this:
>>
>> as.function.foo <- function(obj, ...)
>> {
>> newobj <- function(x, ...){}
>> body(newobj) <- obj
>> return(newobj)
>> }
>>
>> x <- expression(2*x + 3*x^2)
>>
>> foo <- as.function.foo(x)
>> foo(2)
>
> Well, that copies what as.function.polynomial did but that was  
> written for S3 well before R was started.  Here you can use  
> environments:
>
> as.function.foo <- function(obj, ...) function(x, ...) eval(obj)
>


Yes, "did" is the operative word here.    The new  
as.function.polynomial() is considerably slicker
and more general.

But both old and new versions 'unpick' the polynomial "x" into its  
elements
and create a function, line by line, that depends on the elements of  
"x".

The new version uses:

as.function.polynomial <- function (x, ...)
{

<< clever and efficient creation of list "ex"  as a function of vector  
"x" snipped>>

     f <- function(x) NULL
     body(f) <- ex
     f
}


The old version uses:


as.function.polynomial <- function (x, ...)
{

<< clever and efficient creation of character string "jj"  as a  
function of vector "x" snipped>>

    f <- function(x) NULL
     body(f) <- parse(text = jj )[[1]]
    f
}



If f <- as.function.foo(x),  somehow the "f" object has to include  
within itself
the entirety of "x".   In my case, "x" is [of course] an arbitrary- 
dimensional
array of possibly complex elements.

So I can't use Bill/Kurt's method (at least not easily)  because my
object is considerably more complicated than a vector.
And I don't have an example  that works on a complicated object
to copy.


>
>>
>>
>> Hope this help
>>
>> On 14/01/2008, Robin Hankin <r.hankin at noc.soton.ac.uk> wrote:
>>> Antonio
>>>
>>>
>>> thanks for your help here, but it doesn't answer my question.
>>>
>>> Perhaps if I outline my motivation it would help.
>>>
>>>
>>> I want to recreate the ability of
>>> the "polynom" package to do the following:
>>>
>>>
>>> > library(polynom)
>>> > p <- polynomial(1:4)
>>> > p
>>> 1 + 2*x + 3*x^2 + 4*x^3
>>> > MySpecialFunction <- as.function(p)
>>> > MySpecialFunction(1:10)
>>>  [1]   10   49  142  313  586  985 1534 2257 3178 4321
>>> > p <- 4
>>> > MySpecialFunction(1:10)
>>>  [1]   10   49  142  313  586  985 1534 2257 3178 4321
>>> >
>>>
>>>
>>> See how the user can define object "MySpecialFunction",
>>>  which outlives short-lived polynomial "p".
>>>
>>> Unfortunately, I don't see a way to modify as.function.polynomial()
>>> to do what I want.
>>>
>>>
>>> best wishes
>>>
>>>
>>> rksh
>>>

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