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
Copyright © 2021 Jogjafile Inc.
The short answer
No.
The long answer
Incrementing operators are easy to make:
However, these functions don't modify
xdirectly because R tries very hard to prevent functions from modifying variables outside their scope. That is, you still need to writex <- x %+=% 1to actually updatex.The
inc<-anddec<-functions from packageHmiscwork 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 modifiesxoutside 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.tableuser in which case there's no hope for you anyway.