[R] Pass an operator to function

Joshua Wiley jwiley.psych at gmail.com
Wed Dec 1 05:07:25 CET 2010


Here's one way that works with *some* operators (I do not believe you
actually could generalize to *every* operator because some are unary
and some are binary (see example cases).

test <- function(a, op, b) {
  foo <- match.fun(FUN = op)
  return(foo(a, b))
}

test(5, ">", 4)
test(5, "<", 4)
test(5, "+", 4)
test(5, "!", 4) # fails because unary
test(5, "-", 4)
test(5, "*", 4)

HTH,

Josh

On Tue, Nov 30, 2010 at 6:54 PM, randomcz <randomcz at gmail.com> wrote:
>
> Hi guys,
>
> How to pass an operator to a function. For example,
>
> test <- function(a, ">", b)
> {
>      return(a>b) #the operator is passed as an argument
> }
>
> Thanks,
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Pass-an-operator-to-function-tp3066627p3066627.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list