[R] Comparing two functions

baptiste auguie baptiste.auguie at googlemail.com
Sun Nov 28 13:25:31 CET 2010


Hi,

Your function fails for a number of reasons. One of them is your
comparison (use browser() to see what is the value taken by f in your
function). Also, n, mean, min and max could not be extracted from ...
with your construction.

Here's my suggestion,

randomIra = function(f="runif", ...){
switch(f,
       rnorm = do.call(rnorm, c(sd=1, list(...))) ,
       runif = , # will use the next one, which is also the default
       runif(...))
}

randomIra("rnorm", n = 5, mean = 20)
randomIra("runif", n=5, min = 10, max = 25)
randomIra(, n=5, min = 10, max = 25) # default


HTH,

baptiste




On 28 November 2010 11:53, Ira Sharenow <irasharenow100 at yahoo.com> wrote:
> Hi. I am new to R and facing a problem that I cannot solve.
>
>
>
> I am writing some basic functions. Then I would like to have a master function that allows me to call one of the functions which I created, but I cannot figure out how to do so.
>
>
>
> Below is an example. The functions rnormIra and runifIra both seem to work fine. I do not get an error message when entering the definition of the master function randomIra; however, it fails when I use it to call another function.
>
>
>
> Can someone please help?
>
>
>
> Thanks.
>
>
>
> Ira
>
>
>
> rnormIra = function(n, mean) {
>  return(rnorm(n,mean,1))
> }
> rnormIra(10,100) #works fine
>
>
>
> runifIra = function(n,min,max) {
>  return(runif(n,min,max))
> }
> runifIra(5,20,30) #works fine
>
>
>
> randomIra = function(f, ...) {
>  if(f == rnormIra) {
>   return(rnormIra(n,mean))
>  }
>  else {
>        return(runifIra(n,min,max))
>  }
> } #no error messages
>
>
>
> randomIra(rnormIra, n = 5, mean = 20) #FAILS
> randomIra("runifIra", n = 5, min = 10, max = 25) #FAILS
>
> do.call(randomIra,list("rnormIra",5,20)) #FAILS
>
>
>        [[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