Read a table without losing its meaning

Day 7 — From a saved file to a table in R

Data Analysis in Life Sciences

About this lecture

Your supervisor sends a CSV file with lengths of 24 seedlings, and later a results file with many thousands of rows. Remember Day 1: opening a table in a spreadsheet and saving it again can quietly change the data. How do we bring a table into R unchanged, and check that it contains what we think it contains?

Today you will:

  • make sure R is looking in the right folder for the file;
  • import a CSV file into a table and inspect its size, columns and types;
  • tell labels from measurements, and a missing value from a zero;
  • write down what you checked, so someone else can trust the table.

Day 6 typed values by hand. From today the values come from files. Day 8 calculates and plots from the imported table.

Why not just open it in a spreadsheet?

  • Day 1: a spreadsheet turned the gene name SEPT2 into the date 2-Sep.
  • Size limits fail silently too. The old .xls format stops at 65,536 rows; in 2020 this hid about 16,000 positive COVID-19 tests in the UK.
  • read_csv() reads the file and leaves it unchanged on disk. Every check, such as the number of rows, is a line in your script.

An old .xls sheet holds at most 65,536 rows; the rows beyond the limit are not saved, without any warning.

A file on disk, a table in memory

  • As on Day 1, a CSV is plain text: a header line with column names, then one line per row.
  • read_csv() reads it and creates a table object in R’s memory.
  • Changing the object does not change the file. Changing the file does not change the object until you import again.

read_csv reads the saved seedling file into a 24-row, four-column object in R memory.

First: is R looking in the right folder?

> getwd()
[1] "C:/Users/anna/Documents/introcomputing-course"
> file.exists("data/seedlings.csv")
[1] TRUE
  • getwd() prints the folder R works in: your project folder. Your path starts differently.
  • TRUE: there is a data/seedlings.csv inside it.
  • data/seedlings.csv is a relative path: it starts from the project folder, so it works on a classmate’s computer too.

The course project folder contains data with seedlings.csv, next to output and reports.

If you get FALSE: open introcomputing.Rproj from the extracted folder. Do not paste your personal path into the code.

Import and inspect

> library(readr)
> seedlings <- read_csv("data/seedlings.csv",
+                       show_col_types = FALSE)
> dim(seedlings)
[1] 24  4
> head(seedlings)
# A tibble: 6 × 4
  plant_id treatment initial_mm final_mm
  <chr>    <chr>          <dbl>    <dbl>
1 P01      control         25.7     44.3
2 P02      control         24.3     32.3
3 P03      control         18       32.9
4 P04      control         22.2     40.2
5 P05      control         19.6     33  
6 P06      control         24.7     40.7
  • library(readr) loads the package that has read_csv(). Installed once; loaded in every new session.
  • read_csv() reads the file into a table called seedlings. It prints nothing.
  • dim(): 24 rows, 4 columns. All 24 plants arrived.
  • head() shows the first 6 rows only. A tibble is R’s name for this kind of table.
  • Under each column name, its type: <chr> is text, <dbl> is a number.

What does one row mean?

  • One row is one plant. P01: control, 25.7 mm at the start, 44.3 mm seven days later.
  • Two lengths in one row are the same plant measured twice, not two plants.
  • plant_id and treatment are labels; the _mm columns are measurements.
  • The file does not say “mm” or “seven days”: that comes from data/README.md.

Plant IDs and treatments are labels; initial and final lengths are numeric measurements in millimetres.

One column, one vector

> seedlings$initial_mm
 [1] 25.7 24.3 18.0 22.2 19.6 24.7 21.2 23.7
 [9] 25.9 23.2 24.6 22.9 24.0 22.1 20.9 21.5
[17] 25.4 18.7 22.2 18.4 23.6 21.4 22.7 22.4
> length(seedlings$initial_mm)
[1] 24
> mean(seedlings$initial_mm)
[1] 22.47083
  • $ picks one column by name and gives a vector, like those on Day 6.
  • [9] and [17] at the line starts number the values: the 9th, the 17th.
  • 24 values, one per plant.
  • Mean initial length 22.47 mm. Always add the unit: R only sees numbers.
  • This mean mixes both groups, so it says nothing yet about the treatment.

Missing is not zero

> mean(c(10, NA, 20))
[1] NA
> mean(c(10, NA, 20), na.rm = TRUE)
[1] 15
> mean(c(10, 0, 20))
[1] 10
> sum(is.na(seedlings$final_mm))
[1] 0
  • NA = not available: no reading exists. R will not guess, so the mean is NA.
  • na.rm = TRUE leaves it out: mean of two values.
  • Writing 0 invents a plant of zero length.
  • seedlings has 0 missing final lengths.

Leaving out one unavailable reading gives a mean of 15; a genuine zero gives a mean of 10.

Worked example: a second class’s data

> transfer <- read_csv("data/seedlings-transfer.csv",
+                      show_col_types = FALSE)
> dim(transfer)
[1] 18  4
> tail(transfer, 3)
# A tibble: 3 × 4
  plant_id treatment initial_mm final_mm
  <chr>    <chr>          <dbl>    <dbl>
1 T16      treated         20       39.9
2 T17      treated         21       36  
3 T18      treated         21.6     43  
  • Another class repeated the experiment with 18 seedlings. Its description promises 9 plants per group, lengths in mm.
  • A new name, transfer, so seedlings is not overwritten.
  • dim(): 18 rows, 4 columns, the same columns as before.
  • tail() shows the last rows, where head() cannot see problems.

Does it match its description?

> length(unique(transfer$plant_id))
[1] 18
> table(transfer$treatment)

control treated 
      9       9 
> sum(is.na(transfer$final_mm))
[1] 0
  • unique() keeps each ID once: 18 different plants, none listed twice.
  • table() counts each group: 9 and 9.
  • Nothing missing. The table is what the study description promises.

The transfer study has 18 plants, nine per group.

A plausible table can still be the wrong one

  • Two studies can have the same column names. Both import without errors.
  • Check the numbers against the description: 24 plants or 18? 12 or 9 per group?
  • Same for a lab table:
> solutions <- read_csv("data/solutions.csv",
+                       show_col_types = FALSE)
> dim(solutions)
[1] 6 5

Mass (g) and molar mass (g/mol) are both numbers there, but adding them would be meaningless.

Two study folders hold measurement tables with similar columns, one with 24 and one with 18 plant records.

Write down what you checked

A useful import note gives evidence, not just “checked”:

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 data/README.md). Simulated teaching data.

  • Facts from R: rows, columns, types, IDs, group counts, missing values.
  • Facts from the dictionary: units, what one row is, how plants were allocated.

Summary

Idea Key fact
Why code, not a spreadsheet read_csv() leaves the file unchanged; spreadsheets can silently convert or drop data (row limits)
File vs object The CSV stays on disk; the imported table lives in R’s memory
Relative path data/seedlings.csv from the project folder; check with file.exists()
Inspect dim(), names(), str(), head(), tail(): 24 × 4 for seedlings.csv
Rows and columns One row = one plant; IDs and groups are labels; lengths are measurements in mm
Missing NA is not 0; na.rm = TRUE leaves it out of that calculation; report how many
Meaning Units and design come from data/README.md, not from R

Next (Day 8, transform and plot): calculate each plant’s growth as a new column and draw a figure where every point is a plant.

Now: open the Day 7 exercises. Leave with day07.R, which imports and inspects seedlings.csv and leaf-mass.csv and runs from the top after a restart.