[R] Building a function

Prof Brian D Ripley ripley at stats.ox.ac.uk
Thu Aug 1 15:14:23 CEST 2002


On Thu, 1 Aug 2002, Florent BATY wrote:

>   >On Thu, Aug 01, 2002 at 11:44:31AM +0200, Florent BATY wrote:
> />> Hello, /
> />> /
> />> Is it possible to build a function, a posteriori, by getting the names /
> />> of the arguments and the formula in a list or a vector ? When I use
> the /
> />> function as.function(), I don't know how to define explicitly the
> names /
> />> of my variables as formal arguments. /
> />> /
> />> Thanks /
> />> /
> />> /
>
>  >Did you check with the example (in 'help(as.function)') ?
>
>  >If yes, can you give more details ?
>
>  >L.
>
> I did actually but it haven't managed to solve my problem.
>  From an "nls" object, I want to construct a function based on
>     1) the formula:
>
>     > summary(nlsED)$formula[[3]]
>         (t < lag) * log10(x0) + (t > lag) * log10(x0 * exp(mu * (t -
>         lag)))
>
>     2) the arguments of this formula:
>     > all.vars(summary(nlsED)$formula[[3]])
>     [1] "t"   "lag" "x0"  "mu"
>
> Next step should consist in declaring the names of these variables as
> the arguments of the function but I have an Error message:
>
>     >
> as.function(c(alist(all.vars(summary(nlsED)$formula[[3]])),summary(nlsED)$formula[[3]]))
>     Error in
> as.function.default(c(alist(all.vars(summary(nlsED)$formula[[3]])),  :
>         invalid formal argument list for "function"
>
> I managed to construct a function with no arguments in it:
>
>     > as.function(c(summary(nlsED)$formula[[3]]))
>     function ()
>     (t < lag) * log10(x0) + (t > lag) * log10(x0 * exp(mu * (t -
>         lag)))
>
> But I can't define the arguments of this function.
>
> Do you have any ideas ??

alist(all.vars(summary(nlsED)$formula[[3]]))

is not what you think it is.  You do need to contruct an argument list.
Try this

xx <- all.vars(summary(nlsED)$formula[[3]]
xxx <- vector("list", length(xx))
names(xxx) <- xx
Args <- do.call("alist", xxx)
as.function(c(Args, summary(nlsED)$formula[[3]]))

which looks about right

-- 
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 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list