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
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
The short answer
No.
The long answer
Incrementing operators are easy to make:
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 writex <- x %+=% 1
to actually updatex
.The
inc<-
anddec<-
functions from packageHmisc
work around this restriction. So you might be surprised to find that the definition ofinc<-
is just: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 interpretsas
This is how you're able to do things like
names(iris) <- letters[length(iris)]
.%<>%
is magical because it modifiesx
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.