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