[R] Function to Define a Function

Greg Snow Greg.Snow at imail.org
Tue Aug 10 17:46:55 CEST 2010


What if you change your function to:

mdlChooser <- function(type=c("one","two")) {
  type <- match.arg(type)
  switch(type,
    one={ function(x,N0,r) N0*exp(x*r) },
    two={ function(x,N0,r,K) (N0*K)/(N0+(K-N0)*exp(-x*r)) },
  )
}

Does that work for you?

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Derek Ogle
> Sent: Monday, August 09, 2010 7:31 PM
> To: R (r-help at R-project.org)
> Subject: [R] Function to Define a Function
> 
> I am trying to define a general R function that has a function as the
> output that depends on the user's input arguments (this may make more
> sense by looking at the toy example below).  My real use for this type
> of code is to allow a user to choose from many parameterizations of the
> same general model.
> 
> My "issue" is that when I compile a package with this type of code in
> it I get a __warning__ that "multiple local function definitions for
> 'm' with different formal arguments."  While this is not a "deadly
> error" I would like to avoid the warning if possible.  Can someone
> provide some guidance?  Thank you in advance for any help you can
> offer.
> 
> For what it is worth ... I am working on a Windows XP machine with R
> 2.11.1.
> 
> 
> 
> 
> ## A function that allows the user to create a new function that
> depends on their
> ##   choice in the type argument.  As a simple example, if the user
> chooses "one"
> ##   then the output function is exponential growth, if the user choses
> "two" then
> ##   thhe output function is logistic growth.
> 
> mdlChooser <- function(type=c("one","two")) {
>   type <- match.arg(type)
>   switch(type,
>     one={ m <- function(x,N0,r) N0*exp(x*r) },
>     two={ m <- function(x,N0,r,K) (N0*K)/(N0+(K-N0)*exp(-x*r)) },
>   )
>   m
> }
> 
> ## define time steps
> t <- 0:10
> 
> ## create a function -- junk1 -- that produces exponential growth
> junk1 <- mdlChooser("one")
> junk1
> res1 <- junk1(t,500,0.2)
> res1
> 
> ## create a function -- junk2 -- that produces logistic growth
> junk2 <- mdlChooser("two")
> junk2
> res2 <- junk2(t,500,0.2,1000)
> res2
> 
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list