26 + 8[1] 34
At its simplest, R is a very over-powered pocket calculator. Run the code below (click the small “Run Code” button, or press Ctrl/Cmd + Enter) and look at the output.
Congratulations! Assuming you saw the answer 4, you’ve successfully used R to sum 2 and 2.
Using the interactive editor below, add your birth day to your birth month.
In R, the four basic arithmetic operators all behave the way you’d expect.
[1] 4
[1] 8
[1] 12
[1] 15
Before running any code, predict what value each of the following expressions will produce, then use the interactive editor to run the code and check your predictions.
If your predictions matched, great! You’ve already got the core idea. If not, that’s completely fine. Notice which line surprised you, make sure you correctly identified the arithmetic operator involved, and try to work out where your prediction went wrong.
Now let’s use these same tools to solve a slightly more complex problem.
When parsing your commands, R will, mostly, scan each line of code from left to right and apply each mathematical operation according to the usual PEMDAS ordering (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction).
Do: Run the following two lines of code and compare their results.
See: Notice that the two lines produce different answers, even though they use the same three numbers and the same three operators. Why?
4 by 2, and then adds 3 to the result.3 to 4, and only then divide the result by 2.Parentheses are your most reliable tool for controlling order of operations. When in doubt, add parentheses. They never hurt, and they make your intent explicit both to R and to anyone (including future-you) reading the code.
Why do the following two expressions produce different answers?
In the first case, we’ve used parentheses to group the two blocks of addition/subtraction \((3 + 4 - 2 = 5)\) and \((10 - 7 = 3)\). We then multiply those results \((5 \times 3 = 15)\).
In the second case, we rely on R’s rules for operator precedence, so the multiplication \((2 \times 10 = 20)\) is done first. Then we do the addition/subtraction \((3 + 4 - 20 - 7 = -20)\).
Now that you’re aware of R’s rules for operator precedence, let’s revisit the birth day/month problem from above.
Use a single line of code to complete the following calculations.