Assignment: Addition/Subtraction Assignment Operators

AssignmentR Documentation

Addition/Subtraction Assignment Operators

Description

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.

Usage

x %+=% y

x %-=% y

Arguments

x, y

Numeric vectors.

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.

Value

A numeric vector.

Author(s)

Kevin Potter

References

https://stackoverflow.com/questions/5738831

Examples

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

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

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

# Vectorized
x <- 1:3
x %+=% 3
x
x <- 3:1
x %-=% 2:0
x

rettopnivek/camrprojects documentation built on March 26, 2024, 9:17 a.m.