Fundamental Interactions

How This Tutorial Works

Throughout this module, you’ll move through the same four-step cycle for almost everything you learn:

  1. Do — run a small piece of R code.
  2. See — look carefully at what R prints back.
  3. Predict — before you run the next piece of code, guess what will happen.
  4. Explain — put into words why R behaved the way it did.

This cycle might feel slow at first, but it’s the fastest way to build real understanding rather than just copying commands. Let’s try it right now.

R as a Calculator

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.

That’s the whole cycle in miniature: you did something (ran 2 + 2), and you saw something (the number 4). R evaluated the expression and printed the result straight back to you.

The usual arithmetic operators all behave the way you’d expect.

## Add 2 and 2
2 + 2
[1] 4
## Subtract 6 from 14
14 - 6
[1] 8
## Multiply 3 and 4
3 * 4
[1] 12
## Divide 225 by 15
225 / 15
[1] 15
Practice: Predict, Then Run

Before you touch the editor, predict what value each of the following expressions will produce. Write your guess down (even just in your head), then run the code to check yourself.

10 - 3
4 * 4
100 / 4

If your predictions matched, great! You’ve already got the core idea. If not, that’s completely normal at this stage: notice which line surprised you and re-read the operator (-, *, /) involved. Getting comfortable naming why an answer is what it is (not just that it’s correct) is exactly the skill this module is trying to build.

A Slightly Bigger Task

Now let’s use these same tools to solve a tiny real problem, so you can see arithmetic doing something useful rather than just producing numbers in isolation.

Practice
  1. Calculate the number of whole days left in the current month.
  2. Calculate the number of weeks left in the month.
    • Account for partial weeks with a decimal-valued answer.

Start by figuring out (in your head or on paper) how many days the current month has in total, and how many days have already passed. Subtracting those two numbers gets you the days remaining. From there, think about which arithmetic operator turns a number of days into a number of weeks.

At time-of-writing, it’s 18 July. Since July has 31 days, we get 13 days remaining in the month.

31 - 18
[1] 13

To find the number of remaining weeks, I’ll just divide the answer from above by 7.

13 / 7
[1] 1.857143

Once you’re confident with the ideas above, head to the Basic Operators page to build on this foundation with all of R’s arithmetic operators.

Back to top