Dataslope logoDataslope

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

OperatorMeaningExampleResult
+addition2 + 35
-subtraction10 - 46
*multiplication3 * 721
/division10 / 42.5
^exponentiation2 ^ 101024
%%modulo (remainder)17 %% 52
%/%integer division17 %/% 53

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.

Code Block
R 4.6.0

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.

Code Block
R 4.6.0

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).
Code Block
R 4.6.0

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:

ValueMeaning
NA"missing" (not available)
NaN"not a number" (e.g. 0 / 0)
Infpositive infinity (e.g. 1 / 0)
-Infnegative infinity
Code Block
R 4.6.0

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.

OperatorMeaning
==equal to
!=not equal to
<less than
<=less than or equal
>greater than
>=greater than or equal
Code Block
R 4.6.0

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():

Code Block
R 4.6.0

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.

OperatorMeaning
!NOT
&AND (vectorized)
|OR (vectorized)
&&AND (single value, used in if)
||OR (single value, used in if)
Code Block
R 4.6.0

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:

Code Block
R 4.6.0

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:

FunctionWhat 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
Code Block
R 4.6.0

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

QuestionSelect one

What does 10 %% 3 evaluate to in R?

3.33

3

1

30

QuestionSelect one

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

QuestionSelect one

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 decimals
  • total — the total bill (bill + tip), rounded to 2 decimals

Both should be plain numeric scalars.

Challenge
R 4.6.0
Tip calculator

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.

On this page