[R] Using if statement on function

Duncan Murdoch murdoch.duncan at gmail.com
Mon Jun 28 14:59:04 CEST 2010

On 28/06/2010 5:50 AM, Etienne Stockhausen wrote:
> Hello everybody,
> I'm trying to use a if-statment on a function. For a better 
> understanding I want to present a small example:
>     FUN=mean                             # could also be median,sd or 
> any other function
>     if (FUN == mean)
>        plot(...)
>     if (FUN == median)
>        plot(...) 
>     ...
> This doesn't work, because FUN is a function. I've already tried to 
> coerce the type of  FUN with as.character( ), but that's also not 
> possible. I'm stuck with this task and it is absolutely necessary to 
> give FUN  the class of a function.
> I'm looking forward for any hints, clues or solutions for my problem.

You should use identical() to compare two functions:

 > FUN <- mean
 > identical(FUN, mean)
[1] TRUE
 > identical(FUN, median)

all.equal() is probably sufficient for your needs, but it will ignore 
some small differences.

Duncan Murdoch

More information about the R-help mailing list