[r] R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?

Does R have a concept of += (plus equals) or ++ (plus plus) as c++/c#/others do?

This question is related to r operators variable-assignment increment

The answer is


Increment and decrement by 10.

require(Hmisc)
inc(x) <- 10 

dec(x) <- 10

R doesn't have these operations because (most) objects in R are immutable. They do not change. Typically, when it looks like you're modifying an object, you're actually modifying a copy.


Following @GregaKešpret you can make an infix operator:

`%+=%` = function(e1,e2) eval.parent(substitute(e1 <- e1 + e2))
x = 1
x %+=% 2 ; x

R doesn't have a concept of increment operator (as for example ++ in C). However, it is not difficult to implement one yourself, for example:

inc <- function(x)
{
 eval.parent(substitute(x <- x + 1))
}

In that case you would call

x <- 10
inc(x)

However, it introduces function call overhead, so it's slower than typing x <- x + 1 yourself. If I'm not mistaken increment operator was introduced to make job for compiler easier, as it could convert the code to those machine language instructions directly.


We can override +. If unary + is used and its argument is itself an unary + call, then increment the relevant variable in the calling environment.

`+` <- function(e1,e2){
    # if unary `+`, keep original behavior
    if(missing(e2)) {
      s_e1 <- substitute(e1)
      # if e1 (the argument of unary +) is itself an unary `+` operation
      if(length(s_e1) == 2 && 
         identical(s_e1[[1]], quote(`+`)) && 
         length(s_e1[[2]]) == 1) {
        # increment value in parent environment
        eval.parent(substitute(e1 <- e1 + 1, list(e1 = s_e1[[2]])))
      # else unary `+` should just return it's input
      } else e1
    # if binary `+`, keep original behavior
    } else .Primitive("+")(e1, e2)
}

x <- 10
++x
x
# [1] 11

other operations don't change :

x + 2
# [1] 13
x ++ 2
# [1] 13
+x
# [1] 11
x
# [1] 11

Don't do it though, as you'll slow down everything. Or do it in another environment and make sure you don't have big loops on these instructions.

You can also just do this :

`++` <- function(x) eval.parent(substitute(x <- x + 1))
a <- 1
`++`(a)
a
# [1] 2

We released a package, roperators, to help with this kind of thing. You can read more about it here: https://happylittlescripts.blogspot.com/2018/09/make-your-r-code-nicer-with-roperators.html

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

x <- 1:3
x %+=% 1; x
x %-=% 3; x
y <- c('a', 'b', 'c')
y %+=% 'text'; y
y %-=% 'text'; y

# etc

We can also use inplace

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

Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to operators

What is the difference between i = i + 1 and i += 1 in a 'for' loop? Using OR operator in a jquery if statement What is <=> (the 'Spaceship' Operator) in PHP 7? What does question mark and dot operator ?. mean in C# 6.0? Boolean operators ( &&, -a, ||, -o ) in Bash PowerShell and the -contains operator How do I print the percent sign(%) in c Using the && operator in an if statement What do these operators mean (** , ^ , %, //)? How to check if div element is empty

Examples related to variable-assignment

How to assign a value to a TensorFlow variable? Why does foo = filter(...) return a <filter object>, not a list? Creating an array from a text file in Bash Check if returned value is not null and if so assign it, in one line, with one method call Local variable referenced before assignment? Why don't Java's +=, -=, *=, /= compound assignment operators require casting? How do I copy the contents of one ArrayList into another? Python: Assign Value if None Exists Assignment inside lambda expression in Python Expression must be a modifiable L-value

Examples related to increment

How to increment a letter N times per iteration and store in an array? How to increment a number by 2 in a PHP For Loop Can a for loop increment/decrement by more than one? Increment a value in Postgres R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.? Ruby: How to iterate over a range, but in set increments? Increment a database field by 1 Python integer incrementing with ++ What is the difference between i++ & ++i in a for loop? How can I increment a char?