I'm trying to make an 'implies' operator for logical variables in R to make propositional calculus easier. However it doesn't seem to be playing nice with the negation operator. As the last 4 lines here indicate, I have to wrap negated variables in parentheses to get the implication operator to work correctly.
I suspect that operator precedence is the issue but I'm not sure. And from what I read there isn't a way to change an infix operator's precedence. Is there a way I could redefine implies() so that the parentheses in (!q) %->% (!p) wouldn't be necessary?
> implies <- function(p, q) !p | q
> "%->%" <- implies
>
> p <- c(TRUE, TRUE, FALSE, FALSE)
> q <- c(TRUE, FALSE, TRUE, FALSE)
> p %->% q
[1] TRUE FALSE TRUE TRUE
> !q %->% !p
[1] TRUE FALSE FALSE FALSE
> (!q) %->% !p
[1] TRUE FALSE TRUE TRUE
R doesn't have any way to control the operator precedence. It's described in the help page
?Syntax. Your problem is that negation has lower priority than special operators, sois parsed as
Probably the best advice is not to try to use R for the project you're working on, since it's not really designed for that kind of thing. However, what you want might be possible: R allows you to see the parse tree from an expression, and tells where parentheses occur:
Conceivably this could allow you to write a function that could modify the expression to give
!higher precedence than%->%.Alternatively, your function could just do a text substitution to change
%->%or!into a different precedence operator before parsing, and then change it back before evaluation.