How can I make `==` always evaluate to `TRUE`?

Viewed 74

This is perhaps an unusual question. I want to know if it's possible to create an object y in R for which x == y always evaluates to TRUE, or possible NA (e.g. if x is NA), whatever the value of x.

If necessary, y could also be a function call y().

The only way I can think of approaching such a problem is to use sys.call() or sys.calls(), but so far I've had no luck with that approach.

NB, I have no idea why you would need this behaviour, I'm just interested to know if it can be done.

2 Answers

I don’t know of a non-cheat way — your approach of inspecting the call stack is promising but there’s no obvious (to me) way to find the calling expression in the call stack so I couldn’t get this to work.

But if we’re willing to cheat, we can do so easily: every operator can be overridden in R so you can redefine == however you want.

Maybe (slightly) more realistically useful, you can override (group) generics for specific classes. So you could define a class with the desired semantics of comparing TRUE against any other value:

# `==` is part of the `Ops` S3 group generic.
Ops.tautology = function (x, y) TRUE

y = structure(list(), class = 'tautology')
1 == y
# [1] TRUE
2 == y
# [1] TRUE
NA == y
# [1] TRUE

This definition of the group generic is too simplistic in practice: it also redefines + and basically all other standard binary operators. We’d probably want to dispatch just on == but since this is a hack anyway the added complexity isn’t really worth it.

I don't believe that this is possible, if you allow for x to be NA.

Consider the below, where we set both x and y to NA.

x <- NA
y <- NA
x == y
> [1] NA
Related