R is primarily a calculator, and the purpose of this chapter is to show the sytnax for basic arithmetic operations—as taught since primary school—into their R equivalents. These operations are identical across programming languages, so this is not specific to R. Operations follow the standard order of operations (Chapter 1), so attention to precedence is required.
Formal
Addition: symbol + as in a + b
Subtraction: symbol - as in a - b
Multiplication: symbol * as in a * b. Here it is worth noting that this differs from \(a \times b, \; a b, \; \text{and } a.b\), which are mathematical notations, not programming syntax.
Division: symbol / as in a / b. This is also different from \(a \div b\) and \(\frac{a}{b}\), which are mathematical notations rather than programming syntax.
Power: symbol ^ as in a^b.
Parentheses: symbol () as in (a + b)^2. Be careful, as () is also used for functions (Chapter 40). Additionally, {} and [] are not substitutes for parentheses.1
Examples
# Addition: computes the sum of 1 and 11+1
[1] 2
# Negation: evaluates 2 minus 112-11
[1] -9
# Multiplication: calculates 2 times 12*1
[1] 2
# Division: computes the quotient of 1 divided by 21/2
[1] 0.5
# Exponentiation (power): raises 2 to the power of 62^6
[1] 64
# Grouping with parentheses: forces (1 + 1) to evaluate first before multiplying by 3(1+1) *3
[1] 6
Tips and warnings
Here is a list of common mistakes that will display an error message:
Multiplication is often omitted. For example, \(2\pi\) in mathematics is not written as 2 pi in R. Multiplication must be explicit, so the equivalent is 2* pi. The same rule applies to (a + b) * c.
Parentheses come in pairs, and closing parentheses are sometimes forgotten. However, using a good script editor automatically adds the closing parenthesis.
Leaving spaces around expressions improves readability (e.g., a * b instead of a*b).
The modulo (remainder) is implemented using 5%%3.
These arithmetic symbols have special meanings in R, which is why they cannot be used when naming a variable.
Curly brackets are used to group multiple statements into a single code block, and square brackets for indexing and subsetting vectors, matrices, data frames, and lists ↩︎