getwd()
file.exists("data/seedlings.csv")Day 7 — Read a table and find out what it means
Lecture slides · Quiz · Weekly revision
Today’s question
On day 6 you typed plant lengths by hand. The real experiment has 24 seedlings, and their lengths are in data/seedlings.csv. Can we bring that table into R unchanged, and check that it holds what we think it holds: 24 plants, two groups, two lengths each?
The study is described in the data dictionary, data/README.md: 24 seedlings in separate pots, 12 randomly allocated to a nutrient treatment and 12 to a control, each measured at the start and after seven days, in millimetres. These are simulated teaching data. Keep the dictionary open; R can count rows, but only the dictionary tells you what a row means.
Open introcomputing.Rproj and create a new script, day07.R, in the project folder.
Save today: day07.R.
Is R looking in the right folder?
Use getwd() and file.exists() to find out whether R can see the seedling file:
getwd() prints the folder R is working in, which should be your project folder, not data. The second line should print TRUE. The path data/seedlings.csv starts from the project folder, so the same line works on a classmate’s computer, even though their full path is different.
file.exists() says FALSE
You have probably opened a different project, a project inside a ZIP preview, or a folder with an extra level from extraction. Open introcomputing.Rproj from the folder where data, output and reports sit side by side. Do not paste your own full path into the code; it would break on every other computer.
Reading the CSV into R
The readr package provides read_csv(), which reads a CSV file into a table. A package is a collection of extra functions. It is installed once (see the software setup page) and loaded with library() in every new R session.
library(readr)
seedlings <- read_csv("data/seedlings.csv", show_col_types = FALSE)
head(seedlings)
dim(seedlings)
names(seedlings)
str(seedlings)The table is now an object called seedlings in R’s memory; the file on disk is unchanged. head() shows its first six rows. dim() gives 24 rows and 4 columns, so all 24 plants arrived. names() lists the columns, plant_id, treatment, initial_mm and final_mm, and str() shows their types: plant_id and treatment are text (chr), the two lengths are numbers (num). show_col_types = FALSE only hides a message; it does not check anything for you.
The first row says that plant P01, in the control group, was 25.7 mm long at the start and 44.3 mm seven days later. Each row is one plant and each column one variable. The two lengths in a row are the same plant measured twice, so the table describes 24 plants, not 48.
One column at a time
$ takes one column out of the table as a vector, like those you made on day 6:
seedlings$initial_mm
length(seedlings$initial_mm)
mean(seedlings$initial_mm)There are 24 initial lengths, one per plant, and their mean is 22.47 mm. The unit comes from the dictionary: the file only contains numbers. This mean mixes both groups, so it says nothing yet about the treatment.
Missing values
When a measurement was never made, R shows NA, “not available”. It is not a zero: a seedling of length 0 mm is a different thing from a seedling nobody measured.
mean(c(10, NA, 20))
mean(c(10, NA, 20), na.rm = TRUE)
mean(c(10, 0, 20))The first mean is NA, because R will not pretend it knows the missing value. na.rm = TRUE asks R to leave it out, which gives 15 from the two values that exist. Writing 0 instead gives 10, from three values, one of which was invented. When you leave missing values out, say how many there were.
The seedling table
Add each step to day07.R with a short comment giving the answer.
- Use
tail(seedlings)to find out which group the last plant, P24, belongs to. It is treated, with lengths 22.4 and 44.7 mm. - Use
sum(is.na(seedlings$final_mm))to find out how many plants have no final length. The answer is 0:is.na()givesTRUEfor each missing value andsum()counts them. - The file
data/leaf-mass.csvcomes from a different study. Read it into an object calledleaves, and usedim(),names()and the dictionary to find out what one row is. It has 18 rows and 3 columns: one leaf from each of 18 plants, with its area in cm² (leaf_area_cm2) and dry mass in mg (dry_mass_mg). - Restart R (Session → Restart R) and run
day07.Rfrom the top. Everything should come back, and the CSV files are still exactly as supplied.
could not find function "read_csv"
Run library(readr) first; after a restart it has to be run again. If R says there is no package called readr, install it as on the setup page. For column names, copy them from names(seedlings): initial_mm works, initial does not.
A second class’s data
Another class repeated the experiment with 18 seedlings, in data/seedlings-transfer.csv. According to the dictionary, it has the same columns, 9 plants per group, and lengths in mm measured seven days apart. Before you use someone else’s table, check that it matches that description. Create day07-inspection.R for this part.
- Read the file into a new object,
transfer, so that yourseedlingstable is not overwritten. Usedim()to find out how many plants it has: 18 rows, 4 columns. - Use
length(unique(transfer$plant_id))to find out whether any plant appears twice.unique()keeps each ID once, so 18 distinct IDs in 18 rows means every row is a different plant. - Use
table(transfer$treatment)to find out how many plants are in each group: 9 control and 9 treated, as promised. - Use
sum(is.na())on both length columns to find out whether any length is missing (none is), andrange()to find out whether the lengths look like seedlings in mm: initial 20.0 to 28.8 mm, final 36.0 to 46.2 mm. - Write what you found in
reports/transfer-import-audit.txt, as sentences someone else can check. For example: “data/seedlings-transfer.csv: 18 rows × 4 columns, 18 distinct plant IDs, 9 control and 9 treated, no missing lengths. Lengths in mm, seven days apart (from the dictionary).”
transfer$initial gives NULL
The column is called initial_mm. Copy names from names(transfer). If your note says 24 plants, you have looked at seedlings, not transfer.
Solution recipes
The file data/solutions.csv lists six solutions that we will calculate with later. Each row gives a solution ID, the dissolved substance (solute), its mass in g, its molar mass in g/mol, and the final volume in mL. As on day 6, a mole is a unit of amount of substance and the molar mass says how many grams one mole weighs.
- Read the file into
solutions. Before runningstr(), predict which columns are text and which are numbers, then check.solution_idandsoluteare text; the other three are numbers. - Use
dim(),unique(solutions$solute)andsum(is.na())to find out how many solutions there are, which substances, and whether anything is missing: 6 rows, 5 columns, two substances (sodium-chlorideandglucose), nothing missing. - Use
range()onmass_gandmolar_mass_g_molto find out how far each varies: masses from 0.2922 to 2.7024 g, molar masses 58.44 and 180.16 g/mol. Both columns are numbers, but they measure different things, so adding a mass to a molar mass would be meaningless. - Save
reports/solutions-import-audit.txt: the size of the table, what each column means and its unit, and the rule you will use later: amount (mol) = mass / molar mass, concentration = amount / final volume in litres.
Check your understanding
The header line holds the column names. dim() counts only the 24 data rows.
The file contains only names and numbers. Units are written in the dictionary, by people. That is why the column names end in _mm.
day07.R also work in a classmate’s project folder?
It uses the relative path data/seedlings.csv, which starts from whatever project folder is open, not a path containing your user name.
Keep: day07.R. Next: calculate growth and draw a figure.