Skip to content
Back to formatted view

Raw Message

Message-ID: <x2vfxtvoam.fsf@biostat.ku.dk>
Date: 2003-04-04T23:24:49Z
From: Peter Dalgaard
Subject: creating function bodies using body()
In-Reply-To: <OFD5A9F863.8E1E25FF-ON85256CFE.00785D4D@rtp.epa.gov>

Setzer.Woodrow at epamail.epa.gov writes:

> I'm having trouble figuring out how to create a function using "body<-"
> ().  The help file for body() says that the argument should be a list of
> R expressions.  However if I try that I get an error:
> 
> > tmpfun <- function(a, b=2){}
> > body(tmpfun) <- list(expression(z <- a + b),expression(z^2))
> Error in as.function.default(c(formals(f), value), envir) :
>         invalid formal argument list for "function"
> 
> Can someone give me a simple example for doing this?  Thanks!

Like this:

> tmpfun <- function(a, b=2){}
> body(tmpfun) <- quote({z <- a + b; z^2})
> tmpfun(3)
[1] 25

And yes, that help page could do with a rewrite...

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907