R as a Calculator
Get fluent with R's basic arithmetic and comparison operators. Before R is "the language of data science," it is the world's most powerful pocket calculator — and the calculator habits matter.
The very first thing you can do in R is use it as a calculator. This is not a throwaway exercise — every later calculation in every later page builds on what's on this page.
The basic arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | addition | 2 + 3 | 5 |
- | subtraction | 10 - 4 | 6 |
* | multiplication | 3 * 7 | 21 |
/ | division | 10 / 4 | 2.5 |
^ | exponentiation | 2 ^ 10 | 1024 |
%% | modulo (remainder) | 17 %% 5 | 2 |
%/% | integer division | 17 %/% 5 | 3 |
Notice that / always returns a real number (so 10 / 4 is 2.5,
not 2). If you want integer division, R has a dedicated operator
%/%. The two together (17 %/% 5 is 3, and 17 %% 5 is 2)
give you both halves of a division.
Try changing the numbers and re-running. R does not save anything between runs unless you assign to a variable.
Order of operations
R follows standard mathematical order of operations: exponentiation > multiplication and division > addition and subtraction, with parentheses overriding everything.
A good habit: when an expression has more than two operators, parenthesize even when you don't have to. Future readers (and future you) will not have to mentally re-run the precedence rules.
Numbers in R
R has two kinds of numbers you will routinely encounter:
- doubles (the default — floating-point real numbers).
- integers (whole numbers, marked with a trailing
L).
For most practical purposes you can ignore the difference — R will quietly convert between them as needed. The case where it matters is interfacing with other systems (databases, foreign code) that care about the distinction.
Special numeric values
R has a few special "numbers" that pop up in real data analysis:
| Value | Meaning |
|---|---|
NA | "missing" (not available) |
NaN | "not a number" (e.g. 0 / 0) |
Inf | positive infinity (e.g. 1 / 0) |
-Inf | negative infinity |
These special values are critical to understand because real
datasets are full of missing values, and R takes the position that
arithmetic with a missing value should produce a missing value
(rather than silently making one up). We will return to NA in a
dedicated chapter on missing data.
Comparison operators
To ask R questions about values, you use comparison operators.
Each comparison returns a logical value: TRUE or FALSE.
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
< | less than |
<= | less than or equal |
> | greater than |
>= | greater than or equal |
That last line is one of the most famous traps in numeric
computing. 0.1 + 0.2 produces something very slightly different
from 0.3 because of how computers represent decimal fractions in
binary. The right way to compare numbers like this is with
all.equal():
This will return TRUE when the two numbers agree within a tiny
tolerance, which is almost always what you actually want.
Logical operators
Once you have logical values, you can combine them.
| Operator | Meaning |
|---|---|
! | NOT |
& | AND (vectorized) |
| | OR (vectorized) |
&& | AND (single value, used in if) |
|| | OR (single value, used in if) |
For now, use & and | (single ones) — they work on both single
values and vectors. The doubled versions (&& and ||) are only
for single-value logic inside if statements; we will see them
later.
A short worked example
Let us compute the area and perimeter of a rectangle, and check whether it is a "wide" or "tall" rectangle, with one little program:
Notice the pattern again: name your inputs, compute things from
them, name the outputs, then describe what happened. Try changing
width and height and rerunning.
Useful built-in math functions
R ships with dozens of math functions. You will use these often:
| Function | What it does |
|---|---|
abs(x) | absolute value |
sqrt(x) | square root |
exp(x) | e raised to the x |
log(x) | natural logarithm |
log10(x) | base-10 log |
log2(x) | base-2 log |
round(x, n) | round to n decimal places |
floor(x) | round down |
ceiling(x) | round up |
sign(x) | -1 / 0 / 1 depending on sign of x |
max(...) | maximum |
min(...) | minimum |
sum(...) | sum |
mean(...) | average |
The shortcut 1:10 creates the sequence 1, 2, 3, ..., 10. We
will use ranges constantly later.
This little diagram captures most of what you can do with R as a calculator: numbers in, numbers / booleans out.
Test your understanding
What does 10 %% 3 evaluate to in R?
3.33
3
1
30
Which of these is the correct R expression for "is 0.1 + 0.2 approximately equal to 0.3, allowing for floating-point error"?
(0.1 + 0.2) == 0.3
(0.1 + 0.2) ~ 0.3
all.equal(0.1 + 0.2, 0.3)
(0.1 + 0.2) === 0.3
What does 2 + 3 * 4 ^ 2 evaluate to in R?
Hint: precedence order is exponentiation (^), then multiplication (*), then addition (+).
80
196
50
100
Challenge: tip calculator
Build a small tip calculator. Given a bill amount bill (a number)
and a tip percentage tip_pct (a number like 18 for 18%), compute:
tip— the dollar amount of the tip, rounded to 2 decimalstotal— the total bill (bill + tip), rounded to 2 decimals
Both should be plain numeric scalars.
Using bill and tip_pct (both already defined), compute:
tip: the tip amount in dollars, rounded to 2 decimals.total:bill + tip, rounded to 2 decimals.
In the next page we will give names to things — the missing piece that turns calculator work into actual programming.
Your First R Program
Run R for the first time, learn what the prompt is doing, understand how output appears, and write a tiny program that does something useful.
Variables and Assignment
How R stores and retrieves values by name, why R uses the strange-looking `<-` arrow, and how the simple act of naming things is the most underrated skill in programming.