[R] Pass an operator to function
Duncan Murdoch
murdoch.duncan at gmail.com
Wed Dec 1 12:48:20 CET 2010
On 30/11/2010 9:54 PM, randomcz 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,
>
It's much simpler than the other suggestions. Just pass the operator,
and treat it as a function. (Most examples assume you're passing the
name of the operator and have to retrieve the function. No need for
that.) The only complication is that operator names are not generally
seen simply as identifiers by the parser, so they need backquotes when
you refer to them.
So the function can simply be
test <- function(a, op, b) {
op(a,b)
}
and then you put the operator in back quotes to pass it:
> test(4, `<`, 5)
[1] TRUE
> test(4, `>`, 5)
[1] FALSE
Duncan Murdoch
More information about the R-help
mailing list