Using R as a Calculator
Order of Operations
When using R as a calculator, the order of operations is the same as you would have learned back in school.
From highest to lowest precedence:
- Parentheses:
(,) - Exponents:
^or** - Multiply:
* - Divide:
/ - Add:
+ - Subtract:
-
3 + 5 * 2
| Output |
|---|
|
Use parentheses to group operations to force the order of evaluation if it differs from the default or to clarify what you intend.
(3 + 5) * 2
| Output |
|---|
|
This can get unwieldy when not needed but clarifies your intentions. Remember that others may later read your code.
(3 + (5 * (2 ^ 2))) # hard to read
3 + 5 * 2 ^ 2 # clear, if you remember the rules
3 + 5 * (2 ^ 2) # if you forget some rules, this might help
The text after each line of code is called a
"comment." Anything that follows after the hash (or octothorpe) symbol
# is ignored by R when it executes code.
Really small or large numbers get a scientific notation:
2/10000
| Output |
|---|
|
Which is shorthand for "multiplied by 10^XX". So 2e-4
is shorthand for 2 * 10^(-4).
You can write numbers in scientific notation too:
5e3 # Note the lack of minus here
| Output |
|---|
|