[R] Function to Define a Function
Derek Ogle
DOgle at northland.edu
Tue Aug 10 14:48:13 CEST 2010
Gabor ... that worked perfectly. Thank you.
> -----Original Message-----
> From: Gabor Grothendieck [mailto:ggrothendieck at gmail.com]
> Sent: Monday, August 09, 2010 10:20 PM
> To: Derek Ogle
> Cc: R (r-help at R-project.org)
> Subject: Re: [R] Function to Define a Function
>
> On Mon, Aug 9, 2010 at 9:31 PM, Derek Ogle <DOgle at northland.edu> wrote:
> > 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
> >
>
>
> Try this:
>
> mdlChooser <- function(type = c("one", "two")) {
> one <- function(x,N0,r) N0*exp(x*r)
> two <- function(x,N0,r,K) (N0*K)/(N0+(K-N0)*exp(-x*r))
> type <- match.arg(type)
> get(type)
> }
More information about the R-help
mailing list