1 Introduction

Every value in R has a type, and the type decides what you can do with it: you can add two read counts, but not a read count and a gene name. In this lab you will practise the lecture’s topics using small examples from the lab bench. By the end you should be able to:

  • create values of the common data types and check their type,
  • convert between types on purpose (casting), and know that casting is not rounding,
  • recognise when R converts types for you (coercion), and why that can cause silent errors,
  • handle the special values Inf, NaN and NA,
  • use arithmetic, comparison and logical operators,
  • do basic text manipulation on gene names, sample IDs and DNA sequences.

1.1 Data types

The four data types you will use every day:

Type What it holds Lab example
double any number Ct value 24.1, temperature 37.5
integer whole numbers read count 1523L
character text gene "BRCA1", sample "S01"
logical TRUE or FALSE treated? TRUE

Numbers are stored as doubles by default, even whole numbers like 1523. Add L to get an integer: 1523L.

2 Exercises

In all exercises in this course, first try to work out what the result should be, then run the code to check. If the output surprises you, make sure you understand why before you move on. If you get stuck, click the key to reveal example code and output, or ask a TA or the person next to you.

There are often several equally good solutions.

We recommend writing all your code in your R Markdown learning journal (from the first lab). By the end of the course it will be your own R tutorial, with your notes and solutions.

2.1 Getting started

Open RStudio and open your r-course Project (File → Open Project…), so that R works in the right folder. You do not need setwd() when you use a Project.

List all objects in your current R session:

ls()
##  [1] "address"           "answer_box"        "asst"             
##  [4] "blank"             "cnames"            "colonies"         
##  [7] "color_primary"     "color_text"        "combined"         
## [10] "crashes"           "dfr"               "dilution"         
## [13] "doctor"            "drinks"            "eng_output"       
## [16] "fa"                "fa1"               "fa2"              
## [19] "gapminder"         "gene"              "glucose"          
## [22] "knit_walkthrough"  "lego"              "linkoping"        
## [25] "loc"               "lund"              "page_dir"         
## [28] "patients"          "penguins"          "plate"            
## [31] "plate_corrected"   "plate_test"        "r"                
## [34] "readings"          "res"               "s"                
## [37] "sharks"            "stackoverflow"     "umea"             
## [40] "uppsala"           "uppsala2"          "uppsala3"         
## [43] "videogames"        "volume_ml"         "walkthrough_block"
## [46] "wt_colonies"       "wt_imposter"       "wt_mice"          
## [49] "wt_primers"

If you want a clean start, the safest option is Session → Restart R. You can also remove all objects with:

rm(list = ls())

This deletes everything in your environment. It uses functions we have not covered yet; it will make sense after the next lectures.

2.2 Variables and data types

  1. You are recording data for one mouse: its ID is M07, it weighs 23.4 g, it had 6 pups, and it is a knockout (TRUE). Store each value in a well-named variable and check its type with typeof(). Is the number of pups an integer? If not, make it one.

mouse_id <- "M07"
weight_g <- 23.4
n_pups <- 6
knockout <- TRUE

typeof(mouse_id)
typeof(weight_g)
typeof(n_pups)    # "double": plain numbers are doubles
typeof(knockout)

n_pups <- 6L      # the L suffix makes an integer
typeof(n_pups)
## [1] "character"
## [1] "double"
## [1] "double"
## [1] "logical"
## [1] "integer"

A colleague stored the weight as "23.4" (in quotes). What happens if you add 1.5 g to it? How do you fix it?

weight_text <- "23.4"
weight_text + 1.5               # error: you cannot do arithmetic on text
## Error in weight_text + 1.5: non-numeric argument to binary operator
as.numeric(weight_text) + 1.5   # convert first
## [1] 24.9
  1. You have a DNA stock at 250 ng/µL and need 20 µL of a 10 ng/µL dilution. Using variables, calculate how many µL of stock and how many µL of water to mix. (Volume of stock = target concentration × final volume / stock concentration.)

stock_conc <- 250
target_conc <- 10
final_volume <- 20

stock_volume <- target_conc * final_volume / stock_conc
water_volume <- final_volume - stock_volume
stock_volume
water_volume
## [1] 0.8
## [1] 19.2

2.3 Casting is not rounding

  1. You have 250 samples and each plate holds 96. How many plates do you need? Try as.integer(), round(), floor() and ceiling() on 250 / 96. Which one gives the right answer here, and why are the others wrong?

250 / 96
as.integer(250 / 96)   # 2: cuts off decimals, 58 samples have no plate!
round(250 / 96)        # 3, but only by luck: try 200 / 96
floor(250 / 96)        # 2: same problem as as.integer()
ceiling(250 / 96)      # 3: always rounds up, which is what we need
## [1] 2.604167
## [1] 2
## [1] 3
## [1] 2
## [1] 3

2.4 Text, numbers and coercion

  1. A plate reader exported these absorbance values. One well was too bright to measure ("OVER") and one was left empty:
absorbance <- c("0.84", "1.02", "OVER", "0.77", "")

What is the type of absorbance? Convert it to numbers and count how many values became NA. Then calculate the mean absorbance of the wells that were measured.

typeof(absorbance)
abs_num <- as.numeric(absorbance)   # warning: NAs introduced by coercion
abs_num
sum(is.na(abs_num))                 # 2
mean(abs_num, na.rm = TRUE)
## [1] "character"
## [1] 0.84 1.02   NA 0.77   NA
## [1] 2
## [1] 0.8766667

Write a sentence in your journal: "OVER" and "" both became NA, but do they mean the same thing? Would dropping the "OVER" well bias your result?

  1. Predict the type of each result, then check with typeof():
c(TRUE, 2L)
c("37", 5)
c(NA, 1L)
c(NA, "control")

typeof(c(TRUE, 2L))         # integer
typeof(c("37", 5))          # character: the number 5 becomes the text "5"
typeof(c(NA, 1L))           # integer: NA fits into any type
typeof(c(NA, "control"))    # character
## [1] "integer"
## [1] "character"
## [1] "integer"
## [1] "character"

2.5 Special values

  1. Three wells were imaged. Calculate the fraction of infected cells in each well, predicting the result first:
Well Infected cells Total cells
A1 12 40
A2 0 35
A3 0 0

Then calculate the log10 of these viral titres: 1,000,000, 1,000 and 0.

12 / 40   # 0.3
0 / 35    # 0
0 / 0     # NaN: an empty well has no infection rate

log10(1e6)   # 6
log10(1e3)   # 3
log10(0)     # -Inf
## [1] 0.3
## [1] 0
## [1] NaN
## [1] 6
## [1] 3
## [1] -Inf
  1. Plant heights (cm) were measured, but two plants died before measurement:
heights <- c(12.5, NA, 9.8, 15.1, 11.0, NA)

How many values are missing? What is the tallest plant? How many plants are taller than 10 cm? Why do you need na.rm = TRUE in all of them?

sum(is.na(heights))
max(heights)                       # NA
max(heights, na.rm = TRUE)
sum(heights > 10)                  # NA: we don't know about the missing plants
sum(heights > 10, na.rm = TRUE)
## [1] 2
## [1] NA
## [1] 15.1
## [1] NA
## [1] 3

2.6 Operators

  1. In a population with allele frequencies p = 0.65 and q = 1 - p, the Hardy–Weinberg genotype frequencies are p², 2pq and q². Calculate them, then check that they add up to 1, first with == and then with all.equal(). What happened?

p <- 0.65
q <- 1 - p
p^2
2 * p * q
q^2
p^2 + 2 * p * q + q^2 == 1                    # FALSE: rounding errors in decimals
isTRUE(all.equal(p^2 + 2 * p * q + q^2, 1))   # TRUE
## [1] 0.4225
## [1] 0.455
## [1] 0.1225
## [1] FALSE
## [1] TRUE
  1. You seed 100,000 cells that double every 20 hours. How many cells will you have after 72 hours? Use the formula cells = start × 2^(time / doubling time). Then use sprintf() or round() to report it as a whole number.

start_cells <- 1e5
doubling_time <- 20
hours <- 72
cells <- start_cells * 2^(hours / doubling_time)
cells
round(cells)
## [1] 1212573
## [1] 1212573
  1. A study includes patients who are between 18 and 65 years old (inclusive) and have either a BMI above 30 or diabetes. Write one expression that checks this for the patient below. Then change the values to test a few other patients. Why are the brackets important?
age <- 52
bmi <- 27.4
diabetic <- TRUE

age >= 18 & age <= 65 & (bmi > 30 | diabetic)   # TRUE

# A 70-year-old diabetic patient should NOT be included:
age <- 70
age >= 18 & age <= 65 & (bmi > 30 | diabetic)   # FALSE: correct
age >= 18 & age <= 65 & bmi > 30 | diabetic     # TRUE: wrong! & is evaluated before |,
                                                # so every diabetic patient passes
## [1] TRUE
## [1] FALSE
## [1] TRUE
  1. These are the quality scores of eight sequencing reads. How many reads have a quality of at least 30? What fraction of the reads is that? Hint: what does mean() of TRUE/FALSE values give you?
quality <- c(35, 28, 40, 31, 19, 38, 33, 25)

quality >= 30
sum(quality >= 30)    # 5 reads
mean(quality >= 30)   # 0.625: the fraction of TRUE values
## [1]  TRUE FALSE  TRUE  TRUE FALSE  TRUE  TRUE FALSE
## [1] 5
## [1] 0.625
  1. Predict, then run. Explain each surprising result in your journal.
sort(c("S1", "S2", "S10", "S11", "S3"))
"Control" == "control"
sqrt(2)^2 == 2

sort(c("S1", "S2", "S10", "S11", "S3"))   # "S10" and "S11" come before "S2"
"Control" == "control"                    # FALSE: comparisons are case-sensitive
sqrt(2)^2 == 2                            # FALSE: decimals are not stored exactly
isTRUE(all.equal(sqrt(2)^2, 2))           # TRUE
## [1] "S1"  "S10" "S11" "S2"  "S3" 
## [1] FALSE
## [1] FALSE
## [1] TRUE

2.7 Working with text

  1. Here is a PCR primer:
primer <- "ACGTTGCAGGCT"
  • How long is it?
  • Convert it to lower case (hint: ?toupper).
  • Does it start with "ACG"? (Extract the first three bases and compare.)
  • Convert it to RNA by replacing every T with U. Try sub() first, then gsub(). What is the difference?

nchar(primer)
tolower(primer)
substr(primer, start = 1, stop = 3) == "ACG"
sub("T", "U", primer)    # replaces only the first T
gsub("T", "U", primer)   # replaces every T
## [1] 12
## [1] "acgttgcaggct"
## [1] TRUE
## [1] "ACGUTGCAGGCT"
## [1] "ACGUUGCAGGCU"
  1. Build these names with paste(), paste0() and sub():
  • the well names of the first row of a 96-well plate: "A1", "A2", …, "A12",
  • the file names "mouse_1.fastq", "mouse_2.fastq", "mouse_3.fastq",
  • the sample name "S3" from the file name "S3_R1.fastq.gz".

paste0("A", 1:12)
paste0("mouse_", 1:3, ".fastq")
sub("_R1.fastq.gz", "", "S3_R1.fastq.gz")
##  [1] "A1"  "A2"  "A3"  "A4"  "A5"  "A6"  "A7"  "A8"  "A9"  "A10" "A11" "A12"
## [1] "mouse_1.fastq" "mouse_2.fastq" "mouse_3.fastq"
## [1] "S3"
  1. Using sprintf() and your variables from exercise 2, print this pipetting instruction:

Mix 0.80 uL stock with 19.20 uL water

sprintf("Mix %.2f uL stock with %.2f uL water", stock_volume, water_volume)
## [1] "Mix 0.80 uL stock with 19.20 uL water"