1

I'm looking for an implementation of += and -= in R. Anyone built that yet?

a = 1
a += 2 # 3
a -= 2 # -1

tim
  • 3,559
  • 1
  • 33
  • 46

2 Answers2

4

It does not exist in R default operators however you can manage to do something similar to it using roperators package as follows;

install.packages('roperators')
require(roperators)

# Assignment
a <- 1
print(a)
# [1] 1

# To incremenet value
a %+=% 2
print(a)
# [1] 3

# To decrement value
a %-=% 2
print(a)
# [1] 1
Nareman Darwish
  • 1,251
  • 7
  • 14
  • Nice to know about roperators and inplace (below) packages. Was hoping for a solution without the % wrapper. R 6.0 wish list :-) – tim Oct 27 '20 at 15:19
0

We could use inplace operators %+<-% from inplace

library(inplace)
a <- 1
a %+<-% 2

-output

a
#[1] 3

Now, do the subtraction

a %-<-% 2

-output

a
#[1] 1

Or if we want to use the do this as it is, use the reticulate to call python

library(reticulate)
py_run_string("a = 1")
py_run_string("a += 2")
py$a
#[1] 3
akrun
  • 874,273
  • 37
  • 540
  • 662