period_s <- c(2.01, 1.98, 2.05, 1.99, 2.03)
period_s
#> [1] 2.01 1.98 2.05 1.99 2.03
length(period_s)
#> [1] 53 Vectors
In Chapter 2 every name held one number. Physics rarely works that way. You take five readings of a period, or you want the height of a ball at fifty instants, and you want to treat the whole set as one thing. R’s basic object for that is the vector: an ordered sequence of values of the same type. A single number in R is just a vector of length one, which is why every result so far has printed with a [1] in front of it.
3.1 Making vectors
c() combines values into a vector. Here are five stopwatch readings of a pendulum’s period, in seconds:
Typing values by hand is fine for measurements. For regularly spaced values, such as a time axis, use seq(). Give it a start, an end, and either a step (by) or a number of points (length.out):
seq(from = 0, to = 2.5, by = 0.5)
#> [1] 0.0 0.5 1.0 1.5 2.0 2.5
seq(from = 0, to = 1, length.out = 5)
#> [1] 0.00 0.25 0.50 0.75 1.00For steps of exactly one there is a shorthand, the colon, and rep() repeats things:
1:10
#> [1] 1 2 3 4 5 6 7 8 9 10
rep(9.81, times = 3)
#> [1] 9.81 9.81 9.813.2 Arithmetic on whole vectors
This is the idea that makes R read like physics notation. Arithmetic on a vector applies to every element at once. Throw a ball straight up at 12 m/s, and its height is \(y(t) = v_0 t - \tfrac{1}{2} g t^2\). To get the height at a whole set of times, write the formula once:
g <- 9.81 # m/s^2
v0 <- 12 # m/s
t <- seq(from = 0, to = 3, by = 0.5)
y <- v0 * t - g * t^2 / 2
y
#> [1] 0.00000 4.77375 7.09500 6.96375 4.38000 -0.65625 -8.14500There is no loop. t has seven elements, so y has seven elements, one height for each time. The functions from Chapter 2 work the same way: sqrt(t) and sin(t) return a result for every element.
Notice that v0 * t multiplied a single number by a vector of seven. R stretched the single number to match, a rule called recycling. With a single number this is what you want. With two vectors of different lengths R recycles the shorter one too and gives you at most a warning, so if you combine two vectors, make sure they are the same length.
The velocity at each time comes the same way:
v <- v0 - g * t
v
#> [1] 12.000 7.095 2.190 -2.715 -7.620 -12.525 -17.430When two vectors are the same length, arithmetic pairs them up element by element. Here v and y combine to give the energy per unit mass, kinetic plus potential, at each instant:
0.5 * v^2 + g * y
#> [1] 72 72 72 72 72 72 72It is 72 J/kg every time, as it should be.
3.3 Summarizing a vector
A handful of functions boil a vector down to one or two numbers. On the period readings:
sum(period_s)
#> [1] 10.06
mean(period_s)
#> [1] 2.012
sd(period_s)
#> [1] 0.02863564
range(period_s)
#> [1] 1.98 2.05mean() and sd() are the average and the sample standard deviation, the two numbers every lab report asks for. min() and max() return the two ends of range() separately. which.max() answers a slightly different question: not what the largest value is, but where it is.
max(y)
#> [1] 7.095
which.max(y)
#> [1] 3
t[which.max(y)]
#> [1] 1The largest height in y is its third element, at t = 1 s. (The true peak is at \(v_0/g \approx 1.22\) s; a time step of 0.5 s is coarse.) The square brackets are explained in the next section.
Two more functions return vectors rather than single numbers. cumsum() is the running total, and diff() is the difference between each element and the one before it, so it is one element shorter than its input. Dividing differences in position by differences in time gives a numerical derivative:
diff(y) / diff(t)
#> [1] 9.5475 4.6425 -0.2625 -5.1675 -10.0725 -14.9775Those are the average velocities over each half-second interval. Compare them with v above: each lies halfway between the exact velocities at the two ends of its interval. Stepping through time this way is the starting point for the simulations in Chapter 10.
3.4 Picking out elements
Square brackets select elements by position:
y[2]
#> [1] 4.77375
y[c(1, 3)]
#> [1] 0.000 7.095
y[1:3]
#> [1] 0.00000 4.77375 7.09500
y[-1]
#> [1] 4.77375 7.09500 6.96375 4.38000 -0.65625 -8.14500A negative index means “everything except”, so y[-1] drops the first element.
The most useful kind of index is a condition. A comparison on a vector gives a vector of TRUE and FALSE, one per element, and putting that in the brackets keeps the elements where it is TRUE:
y > 0
#> [1] FALSE TRUE TRUE TRUE TRUE FALSE FALSE
y[y > 0]
#> [1] 4.77375 7.09500 6.96375 4.38000
t[y > 0]
#> [1] 0.5 1.0 1.5 2.0The ball is above the ground at four of the seven times. The last line uses a condition on one vector to pick from another, which works because t and y line up element for element. Since TRUE counts as 1 and FALSE as 0 in arithmetic, sum(y > 0) counts how many elements pass the test, and mean(y > 0) gives the fraction.
Elements can also have names, and then you can index by name. This is a tidy way to keep a few related constants together:
g_ms2 <- c(earth = 9.81, moon = 1.62, mars = 3.71)
g_ms2["moon"]
#> moon
#> 1.623.5 Missing values
Real data has holes. Someone fumbles the stopwatch and one trial is lost. R marks a missing value with NA:
trial_s <- c(2.01, 1.98, NA, 1.99, 2.03)
mean(trial_s)
#> [1] NA
mean(trial_s, na.rm = TRUE)
#> [1] 2.0025The mean of a set that includes an unknown number is unknown, so R says NA. Passing na.rm = TRUE tells the function to remove the missing values first. sum(), sd(), min(), max(), and range() all take the same argument.
3.6 Text and logical vectors
The other two types from Chapter 2 make vectors too. A character vector holds text and a logical vector holds TRUE and FALSE:
planet <- c("Earth", "Moon", "Mars")
has_atmosphere <- c(TRUE, FALSE, TRUE)
planet[has_atmosphere]
#> [1] "Earth" "Mars"
class(planet)
#> [1] "character"A vector has exactly one type. If you mix them, R quietly converts everything to the most general one, so c(1.5, "fast") becomes two pieces of text, and you cannot do arithmetic on text. When a column of numbers refuses to add up, a stray character value is the usual cause.
3.7 Vectors in the physics sense
A force or a velocity with three components is also just a numeric vector of length three. R has no special type for it and does not need one. The magnitude is the square root of the sum of the squared components, and the dot product is the sum of the elementwise products:
force_n <- c(3, 4, 12) # N
displacement_m <- c(2, 0, 0.5) # m
sqrt(sum(force_n^2)) # magnitude, N
#> [1] 13
sum(force_n * displacement_m) # work done, J
#> [1] 12Be careful with one thing: force_n * displacement_m on its own is the elementwise product, a vector of three numbers, not the dot product. You have to sum() it.
3.8 A quick look
The fastest way to check a long vector is to draw it. Base R’s plot() takes the horizontal values, then the vertical values, and type = "l" joins the points with a line instead of drawing dots:
t <- seq(from = 0, to = 2.4, length.out = 300)
y <- v0 * t - g * t^2 / 2
plot(t, y, type = "l")
Changing the time axis and rerunning one formula redid the whole calculation at 300 points. The plot is a one-line sanity check. Figures fit for a lab report come from ggplot2 in Chapter 8. Before that, Chapter 4 shows how to wrap a formula like this one in a function of your own.