Extending the incremental operator

I wanted to extend the infix incremental operator to allow it to be equivalent to either the += operator from python or the eponymous ++ operator from C++ where the operator would add one to the current value if a second argument wasn’t entered.

 pp <- function(x, y) {
    if (missing(y)) {
        eval.parent(substitute(x <- (x + 1)))
    } else {
        eval.parent(substitute(x <- x + y))
    }
}

This gives:

 x <- 1
pp(x)
[1] 2
 
pp(x, 10)
[1] 12

What I would really love is an infix operator that can run when one of the two required arguments are missing, ie, a world in which this code runs:

 `%+%` <- function(x, y) {
    if (missing(y)) {
        eval.parent(substitute(x <- (x + 1)))
    } else {
        eval.parent(substitute(x <- x + y))
    }
}
 
x <- 1
x %+% 
x
[1] 2

Leave a comment