elegant increment operator as pipeline

235 views Asked by At
library(magrittr)
x <- 2
x %<>% 
  add(3) %>% 
  subtract(1)
x

Is there predefined a more readable way that works with pipes?

Perhaps something like x %+=% 3 %-=% 1

1

There are 1 answers

9
shadowtalker On

The short answer

No.

The long answer

Incrementing operators are easy to make:

%+=% <- function (x, inc) x + inc
%-=% <- function (x, dec) x - dec

However, these functions don't modify x directly because R tries very hard to prevent functions from modifying variables outside their scope. That is, you still need to write x <- x %+=% 1 to actually update x.

The inc<- and dec<- functions from package Hmisc work around this restriction. So you might be surprised to find that the definition of inc<- is just:

function (x, value) 
{
    x + value
}

That is, the code inside the function is exactly the same as in our custom %+=% operator. The magic happens because of a special feature in the R parser, which interprets

inc(x) <- 1

as

x <- `inc<-`(x, 1)

This is how you're able to do things like names(iris) <- letters[length(iris)].

%<>% is magical because it modifies x outside its scope. It is also very much against R's coding paradigm*. For that reason, the machinery required is complicated. To implement %+=% the way you'd like, you would need to reverse-engineer %<>%. Might be worth raising as a feature request on their GitHub, though.

*Unless you're a data.table user in which case there's no hope for you anyway.