[R] Function to Define a Function
Thomas Lumley
tlumley at u.washington.edu
Tue Aug 10 18:13:46 CEST 2010
On Mon, 9 Aug 2010, Derek Ogle 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.
<snip>
>
> 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
> }
>
One approach is to put the assignment outside the switch
mdlChooser <- function(type=c("one","two")) {
type <- match.arg(type)
m<- 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)) },
)
m
}
or not even assign the result
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)) ,
)
}
-thomas
Thomas Lumley
Professor of Biostatistics
University of Washington, Seattle
More information about the R-help
mailing list