The operator %+=% adds the right operand to a variable and assigns the resulting value to the variable. The operator %-=% subtracts the right operand from a variable and assigns the resulting value to the variable.

x %+=% y

x %-=% y

Arguments

x, y

Numeric vectors.

Value

A numeric vector.

Details

Care must be taken with order of operations. Because %+=% and %-=% are functions, they and their arguments will be evaluated first, followed by subsequent operations. Hence a call like x %+=% 1/2 will not result in an increment of 0.5 to x. Instead, x will be first be incremented by 1. Then the call x/2 will be run with no assignment of values.

References

https://stackoverflow.com/questions/5738831/r-plus-equals-and-plus-plus-equivalent-from-c-c-java-etc

Examples

# Simple assignment
x <- 1
x %+=% 1
x
#> [1] 2
y <- 1
y %-=% 2
y
#> [1] -1

# Order of operations can be tricky
x <- 1
y <- 1
invisible(x %+=% y / 2)
x
#> [1] 2
# Above is equivalent to (x %+=% y)/2

# Therefore embed multiple operations in parentheses
x <- 1
y <- 1
x %+=% (y / 2)
x
#> [1] 1.5

# Vectorized
x <- 1:3
x %+=% 3
x
#> [1] 4 5 6
x <- 3:1
x %-=% 2:0
x
#> [1] 1 1 1