[R] Comparing two functions

Gabor Grothendieck
Sun, 28 Nov 2010 12:58:10 -0000

On Sun, Nov 28, 2010 at 5:53 AM, 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.
>
> 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
>

Try this:

randomIra <- function(f, ...) if (identical(f, rnormIra))
rnormIra(...) else runifIra(...)

--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com