pendulum_small <- data.frame(
length_m = c(0.2, 0.4, 0.6, 0.8),
time_10_s = c(8.98, 12.71, 15.52, 17.93)
)
pendulum_small
#> length_m time_10_s
#> 1 0.2 8.98
#> 2 0.4 12.71
#> 3 0.6 15.52
#> 4 0.8 17.935 Data Frames
A lab notebook is a table. Each row is one measurement, each column is one quantity you wrote down: the length of the string, which trial it was, what the stopwatch said. R’s structure for this is the data frame, and nearly all the data you handle in R will live in one.
A data frame is a set of vectors of equal length, lined up side by side as columns. Everything you learned about vectors in Chapter 3 still applies to each column.
5.1 Building a data frame
Suppose you time a pendulum. Timing a single swing by hand is hopeless, so you time ten full swings and divide later. Here are four measurements at four string lengths:
Each argument to data.frame() is a column: a name, then a vector. The vectors must be the same length, because a table with a ragged edge is not a table. The numbers 1 to 4 down the left side are row labels that R adds, not data.
5.2 Reading a CSV file
Real data arrives in a file, most often a CSV (“comma-separated values”): plain text with one row per line and commas between the columns. Every spreadsheet program can save one.
The pendulum.csv file you downloaded in Chapter 1 is a fuller version of the pendulum experiment: nine lengths from 0.2 m to 1.0 m, three trials at each. read.csv() turns the file into a data frame:
pendulum <- read.csv("data/pendulum.csv")The path "data/pendulum.csv" is a relative path: it starts from the working directory, the folder R is currently looking in. getwd() tells you which one that is. Inside the RStudio project from Chapter 1 it is the project folder.
If R says cannot open file ... No such file or directory, the file is not where the path says it is. Check the spelling, then check getwd().
5.3 Looking at what you have
Always look at data right after reading it. head() shows the first six rows:
head(pendulum)
#> length_m trial time_10_s
#> 1 0.2 1 8.98
#> 2 0.2 2 8.95
#> 3 0.2 3 8.99
#> 4 0.3 1 11.07
#> 5 0.3 2 10.95
#> 6 0.3 3 10.94str(), for “structure”, is the most useful single summary. It gives the size, then each column with its type and first few values:
str(pendulum)
#> 'data.frame': 27 obs. of 3 variables:
#> $ length_m : num 0.2 0.2 0.2 0.3 0.3 0.3 0.4 0.4 0.4 0.5 ...
#> $ trial : int 1 2 3 1 2 3 1 2 3 1 ...
#> $ time_10_s: num 8.98 8.95 8.99 11.07 10.95 ...That is 27 rows (9 lengths times 3 trials) and 3 columns. num is numeric, and int is integer, a numeric column that holds only whole numbers. The pieces are also available separately:
nrow(pendulum)
#> [1] 27
ncol(pendulum)
#> [1] 3
names(pendulum)
#> [1] "length_m" "trial" "time_10_s"summary() gives the minimum, quartiles, mean, and maximum of every column, which is a fast way to catch a typo like a time of 179.3 seconds:
summary(pendulum)
#> length_m trial time_10_s
#> Min. :0.2 Min. :1 Min. : 8.95
#> 1st Qu.:0.4 1st Qu.:1 1st Qu.:12.66
#> Median :0.6 Median :2 Median :15.55
#> Mean :0.6 Mean :2 Mean :15.12
#> 3rd Qu.:0.8 3rd Qu.:3 3rd Qu.:17.95
#> Max. :1.0 Max. :3 Max. :20.085.4 Columns
The $ operator pulls one column out of a data frame as an ordinary vector:
pendulum$time_10_s
#> [1] 8.98 8.95 8.99 11.07 10.95 10.94 12.68 12.65 12.76 14.20 14.14 14.17
#> [13] 15.50 15.56 15.55 16.76 16.79 16.79 17.94 17.96 17.93 18.95 18.99 19.02
#> [25] 20.01 20.08 20.05Since it is a vector, vector functions work on it:
mean(pendulum$time_10_s)
#> [1] 15.12444Assigning to a column name that does not exist yet creates the column. The period of the pendulum is the time for ten swings divided by ten:
pendulum$period_s <- pendulum$time_10_s / 10
head(pendulum, 3)
#> length_m trial time_10_s period_s
#> 1 0.2 1 8.98 0.898
#> 2 0.2 2 8.95 0.895
#> 3 0.2 3 8.99 0.899The division happens for all 27 rows at once, with no loop.
5.5 Rows and columns by index
A vector takes one index in its square brackets. A data frame takes two, separated by a comma: rows first, then columns.
pendulum[2, 3]
#> [1] 8.95
pendulum[1:3, c("length_m", "period_s")]
#> length_m period_s
#> 1 0.2 0.898
#> 2 0.2 0.895
#> 3 0.2 0.899Leave one side of the comma empty to mean “all of them”. So pendulum[5, ] is the whole fifth row and pendulum[, 1] is the whole first column.
The logical indexing from Chapter 3 is how you filter rows. Put a condition in the row slot, and you get the rows where it is true. Here > compares the whole length_m column with 0.8 and gives one TRUE or FALSE per row:
long_strings <- pendulum[pendulum$length_m > 0.8, ]
long_strings
#> length_m trial time_10_s period_s
#> 22 0.9 1 18.95 1.895
#> 23 0.9 2 18.99 1.899
#> 24 0.9 3 19.02 1.902
#> 25 1.0 1 20.01 2.001
#> 26 1.0 2 20.08 2.008
#> 27 1.0 3 20.05 2.005The rows keep their original labels, 22 to 27.
5.6 Lists
A vector holds values of one type. A list can hold anything: numbers, text, vectors of different lengths, even other lists. You make one with list(), usually giving each element a name:
run <- list(
experiment = "simple pendulum",
bob_mass_kg = 0.05,
lengths_m = c(0.2, 0.4, 0.6, 0.8)
)$ gets an element by name, and double square brackets get it by name or by position:
run$bob_mass_kg
#> [1] 0.05
run[["lengths_m"]]
#> [1] 0.2 0.4 0.6 0.8
run[[1]]
#> [1] "simple pendulum"There are two reasons to know this much about lists. First, a data frame is a list of its columns, which is why $ works on both. Second, many R functions return several results bundled into a list. The fits in Chapter 9 come back as lists.
5.7 A summary and a plot
Three trials at each length should be averaged. In base R, aggregate() does it:
period_means <- aggregate(period_s ~ length_m, data = pendulum, FUN = mean)
period_means
#> length_m period_s
#> 1 0.2 0.8973333
#> 2 0.3 1.0986667
#> 3 0.4 1.2696667
#> 4 0.5 1.4170000
#> 5 0.6 1.5536667
#> 6 0.7 1.6780000
#> 7 0.8 1.7943333
#> 8 0.9 1.8986667
#> 9 1.0 2.0046667Read period_s ~ length_m as “period, grouped by length”. The result is a new data frame with one row per length. This works, but the call is hard to remember, and adding a second summary, such as the spread of the three trials, makes it worse. Chapter 7 has a more readable way.
plot(), from Chapter 3, takes two columns as readily as two vectors. Its xlab and ylab arguments label the axes:
plot(pendulum$length_m, pendulum$period_s,
xlab = "Length (m)", ylab = "Period (s)")
The points rise but bend over, as they should if the period goes as the square root of the length: \(T = 2\pi\sqrt{L/g}\). The three trials at each length sit almost on top of each other, which says the timing was consistent.
5.8 Saving a data frame
write.csv() is the reverse of read.csv(). Give it a data frame and a path:
write.csv(period_means, "data/pendulum_means.csv", row.names = FALSE)Always include row.names = FALSE. Without it, R writes the row labels 1, 2, 3 as an extra unnamed column, and you get a junk column the next time you read the file.
One term you will run into: a factor is R’s type for a categorical variable, a column whose values come from a fixed set of labels, such as “steel”, “brass”, “aluminum”. Factors come up once, in Chapter 8.
That is base R’s toolkit for tables, and it is enough to do real work. The dollar signs and repeated pendulum$ do pile up, though. The next part of the book introduces the tidyverse, a set of packages that do the same jobs with code that reads closer to a sentence, starting with Chapter 6.