Skip to main content

2  R as a Calculator

The quickest way to start using R is to treat it as a calculator that never loses your working. Everything here can be typed straight into the Console from Chapter 1.

2.1 Arithmetic

The four basic operators are what you would guess, and ^ raises to a power.

3 + 4
#> [1] 7
10 - 2.5
#> [1] 7.5
6 * 7
#> [1] 42
9.81 / 2
#> [1] 4.905
2^10
#> [1] 1024

Spaces around operators are optional. Two more operators are worth knowing. %/% is integer division and %% gives the remainder. A stopwatch reading of 200 seconds is 3 whole minutes with 20 seconds left over:

200 %/% 60
#> [1] 3
200 %% 60
#> [1] 20

R follows the usual order of operations: powers first, then multiplication and division, then addition and subtraction. Parentheses override it, exactly as on paper.

2 + 3 * 4
#> [1] 14
(2 + 3) * 4
#> [1] 20
-2^2
#> [1] -4
(-2)^2
#> [1] 4

The third line catches people. The power is applied before the minus sign, so -2^2 is \(-(2^2)\). When in doubt, add parentheses.

2.2 Scientific notation

Physics is full of numbers that are too large or too small to type out. Write them with e, which means “times ten to the power of”.

3e8
#> [1] 3e+08
6.674e-11
#> [1] 6.674e-11
1.5e3 * 2e-3
#> [1] 3

So 3e8 is \(3 \times 10^8\) and 6.674e-11 is \(6.674 \times 10^{-11}\). R prints in this notation too, whenever that is the shorter way to write a number.

2.3 Built-in functions and pi

The usual mathematical functions are built in. You call one by writing its name followed by its input in parentheses.

sqrt(2)
#> [1] 1.414214
exp(1)
#> [1] 2.718282
log(100)
#> [1] 4.60517
log10(100)
#> [1] 2

Notice that log() is the natural logarithm, the one your textbook writes as \(\ln\). For base 10, use log10().

The constant pi is built in, and the trigonometric functions take angles in radians, not degrees.

pi
#> [1] 3.141593
sin(pi / 2)
#> [1] 1
sin(90)
#> [1] 0.8939967

sin(90) is the sine of 90 radians, which is not what anyone launching a projectile at 90 degrees wants. To convert degrees to radians, multiply by pi / 180:

sin(30 * pi / 180)
#> [1] 0.5
cos(60 * pi / 180)
#> [1] 0.5

Both are one half, as they should be.

2.4 Storing values with names

A calculation is more useful when you can keep the result. The assignment arrow <- stores a value under a name. Type it as a less-than sign and a hyphen, or press Alt and the minus key in RStudio (Option and minus on a Mac).

mass_kg <- 0.145
speed_m_s <- 40

Assignment prints nothing. To see a value, type its name. To use it, put the name in a calculation. This is the kinetic energy, \(\frac{1}{2}mv^2\), of a baseball thrown at 40 m/s:

mass_kg
#> [1] 0.145
kinetic_energy_j <- 0.5 * mass_kg * speed_m_s^2
kinetic_energy_j
#> [1] 116

That is 116 joules. Every name you create also shows up in RStudio’s Environment pane.

Names can contain letters, digits, underscores, and dots, and should start with a letter. They cannot contain spaces, and they are case-sensitive, as the object not found error in Chapter 1 showed.

This book writes names in lowercase with underscores between words, a style called snake_case, and puts the unit at the end: mass_kg, speed_m_s, length_m. R knows nothing about units. It will happily add meters to seconds. The name is the only place the unit lives, so it is worth the extra letters.

2.5 Function arguments

The inputs to a function are called arguments. Many functions take more than one, separated by commas, and each argument has a name. round() takes a number and how many decimal places to keep; signif() takes a number and how many significant figures to keep.

round(kinetic_energy_j / 3, digits = 2)
#> [1] 38.67
signif(299792458, digits = 3)
#> [1] 3e+08
round(2.71828, 2)
#> [1] 2.72

You can leave the name out, as in the last line, and R matches the arguments by position. Naming them makes code easier to read, and this book usually names everything after the first argument. The help page, ?round, lists a function’s arguments.

Rounding is for the number you report at the end. Keep full precision in the stored values and round only what you print.

2.6 Three short calculations

Names and scientific notation together make a formula read almost as it does on paper. Newton’s law of gravitation, \(F = G m_1 m_2 / r^2\), gives the force between the Earth and the Moon:

gravitational_constant <- 6.674e-11   # N m^2 / kg^2
mass_earth_kg <- 5.972e24
mass_moon_kg <- 7.348e22
distance_m <- 3.844e8                 # average Earth-Moon distance

force_n <- gravitational_constant * mass_earth_kg * mass_moon_kg / distance_m^2
force_n
#> [1] 1.982022e+20

About \(2 \times 10^{20}\) newtons.

A ball launched at speed \(v_0\) and angle \(\theta\) above level ground lands a distance \(R = v_0^2 \sin(2\theta) / g\) away, ignoring air resistance. The angle has to be converted to radians first.

launch_speed_m_s <- 20
launch_angle_deg <- 30
g <- 9.81                             # m/s^2

launch_angle_rad <- launch_angle_deg * pi / 180
range_m <- launch_speed_m_s^2 * sin(2 * launch_angle_rad) / g
range_m
#> [1] 35.31194
round(range_m, digits = 1)
#> [1] 35.3

To try a different angle, change launch_angle_deg and run the lines again. That is the advantage over a pocket calculator: the working is written down and can be rerun.

The third calculation is the baseball’s kinetic energy from earlier. Here it is converted to electron volts, a unit no sports broadcaster uses:

kinetic_energy_j / 1.602e-19          # in electron volts
#> [1] 7.240949e+20

2.7 Comparisons and logical values

Comparison operators ask a yes-or-no question and return TRUE or FALSE. They are <, >, <=, >=, == for “is equal to”, and != for “is not equal to”.

range_m > 30
#> [1] TRUE
launch_angle_deg == 30
#> [1] TRUE
mass_moon_kg != mass_earth_kg
#> [1] TRUE

Testing equality takes two equals signs. A single = means something else in R, and mixing them up is a common early mistake.

2.8 Floating point

R stores numbers in binary with about 16 significant digits, so most decimal values are held with a tiny rounding error. Those errors show up when you test for exact equality:

sqrt(2)^2
#> [1] 2
sqrt(2)^2 == 2
#> [1] FALSE
sqrt(2)^2 - 2
#> [1] 4.440892e-16

The printed value looks like 2, but it differs from 2 around the sixteenth decimal place. Every programming language does this. To ask whether two numbers are equal for practical purposes, use all.equal(), wrapped in isTRUE() so that the answer is always a plain TRUE or FALSE:

isTRUE(all.equal(sqrt(2)^2, 2))
#> [1] TRUE

It bites in ordinary calculations too. The baseball’s kinetic energy printed as 116, but 0.145 has no exact binary form:

kinetic_energy_j == 116
#> [1] FALSE
isTRUE(all.equal(kinetic_energy_j, 116))
#> [1] TRUE
WarningDo not test measured or calculated numbers with ==

Use == for whole numbers you typed in and for text. For anything that came out of a calculation, compare with isTRUE(all.equal(a, b)), or check that the difference is smaller than some tolerance you choose.

2.9 Types of values

Every value in R has a type, and three of them cover almost everything in this book. Numbers are numeric. Text, written inside quotation marks, is character. The values TRUE and FALSE are logical. The function class() tells you which one you have.

class(9.81)
#> [1] "numeric"
class("pendulum")
#> [1] "character"
class(TRUE)
#> [1] "logical"
class(range_m > 30)
#> [1] "logical"

The quotation marks matter. "9.81" is text that happens to look like a number, and R will refuse to do arithmetic with it. TRUE and FALSE are written in capitals, with no quotation marks.

So far every name has held a single number. A real experiment produces many: ten timings, fifty positions. R’s answer to that is the vector, which is the subject of Chapter 3.