1 Introduction

Loops, decisions and functions let you write your analysis once and run it on any number of samples. In this lab you will:

  • repeat steps with for and while loops,
  • store loop results the efficient way,
  • compare loops with vectorised code,
  • make decisions with if, else if, else and ifelse(),
  • write your own functions, with default arguments and input checks,
  • combine all three.

As always: predict first, then run. If the output surprises you, find out why. Click the key to reveal example code. Keep your code and notes in your R Markdown learning journal.

2 Loops

  1. You sequenced five samples:
sample_ids <- c("liver_1", "liver_2", "brain_1", "brain_2", "heart_1")
reads <- c(21.4, 18.9, 25.2, 9.7, 22.8)   # million reads

Write a for loop that prints one line per sample, e.g. liver_1: 21.4 million reads.

for (i in seq_along(sample_ids)) {
  cat(sample_ids[i], ": ", reads[i], " million reads\n", sep = "")
}
## liver_1: 21.4 million reads
## liver_2: 18.9 million reads
## brain_1: 25.2 million reads
## brain_2: 9.7 million reads
## heart_1: 22.8 million reads
  1. In qPCR, the relative amount of a target compared with a reference gene is 2^−ΔCt, where ΔCt = Ct(target) − Ct(reference). Calculate it for these six wells with a for loop. Create the result vector before the loop. Then do the same without a loop, and check that both give the same result.
ct_target <- c(24.3, 25.1, 23.8, 28.9, 29.4, 28.6)
ct_ref    <- c(18.1, 18.3, 17.9, 18.2, 18.0, 18.4)

rel_amount <- numeric(length(ct_target))
for (i in seq_along(ct_target)) {
  rel_amount[i] <- 2^-(ct_target[i] - ct_ref[i])
}
rel_amount

rel_amount_vec <- 2^-(ct_target - ct_ref)   # vectorised
identical(rel_amount, rel_amount_vec)
## [1] 0.0136023526 0.0089742059 0.0167464604 0.0006011447 0.0003700480
## [6] 0.0008501470
## [1] TRUE
  1. Here is a small count table: 1,000 genes in 6 samples.
set.seed(1)
counts <- matrix(rpois(6000, lambda = 50), nrow = 1000,
                 dimnames = list(paste0("gene", 1:1000), paste0("S", 1:6)))

Use a for loop to calculate the total count of each sample (each column). Check your result with colSums().

totals <- numeric(ncol(counts))
for (j in seq_len(ncol(counts))) {
  totals[j] <- sum(counts[, j])
}
totals
colSums(counts)
all(totals == colSums(counts))
## [1] 49794 49928 50382 49911 50285 49929
##    S1    S2    S3    S4    S5    S6 
## 49794 49928 50382 49911 50285 49929 
## [1] TRUE
  1. Why do we create totals before the loop, instead of starting with totals <- c() and adding each new value with totals <- c(totals, ...)? Try both ways with a loop over 100,000 elements and use system.time() to compare.

n <- 1e5
system.time({
  grow <- c()
  for (i in 1:n) grow <- c(grow, i)
})
system.time({
  fill <- numeric(n)
  for (i in 1:n) fill[i] <- i
})
# Growing copies the whole vector at every step, so it gets slower and slower.
##    user  system elapsed 
##   5.791   0.027   5.819 
##    user  system elapsed 
##   0.003   0.000   0.003
  1. A bacterial culture starts with 100 cells and doubles every 20 minutes. Use a while loop to find out how many minutes it takes to reach at least one million cells.

n_cells <- 100
minutes <- 0
while (n_cells < 1e6) {
  n_cells <- n_cells * 2
  minutes <- minutes + 20
}
minutes
n_cells
## [1] 280
## [1] 1638400

3 Decisions

  1. Fasting blood glucose (mmol/L) is classified as normal below 5.6, prediabetes from 5.6 up to 7.0, and diabetes from 7.0. Write an if / else if / else that classifies one value. Test it with 5.2, 6.1 and 7.4.

glucose <- 6.1
if (glucose >= 7.0) {
  "diabetes"
} else if (glucose >= 5.6) {
  "prediabetes"
} else {
  "normal"
}
## [1] "prediabetes"
  1. Classify all patients below, first with a for loop and then with nested ifelse(). Count how many patients fall in each class with table().
glucose_all <- c(5.2, 6.1, 7.4, 4.9, 5.6, 8.2, 6.9, 5.0)

class_loop <- character(length(glucose_all))
for (i in seq_along(glucose_all)) {
  if (glucose_all[i] >= 7.0) {
    class_loop[i] <- "diabetes"
  } else if (glucose_all[i] >= 5.6) {
    class_loop[i] <- "prediabetes"
  } else {
    class_loop[i] <- "normal"
  }
}
class_loop

class_vec <- ifelse(glucose_all >= 7.0, "diabetes",
                    ifelse(glucose_all >= 5.6, "prediabetes", "normal"))
identical(class_loop, class_vec)
table(class_vec)
## [1] "normal"      "prediabetes" "diabetes"    "normal"      "prediabetes"
## [6] "diabetes"    "prediabetes" "normal"     
## [1] TRUE
## class_vec
##    diabetes      normal prediabetes 
##           2           3           3
  1. Here is a sample sheet with columns of different types:
sheet <- data.frame(
  sample   = c("liver_1", "liver_2", "brain_1", "brain_2"),
  rin      = c(8.4, 7.9, 6.2, 9.1),
  reads_m  = c(21.4, 18.9, 25.2, 9.7),
  passed   = c(TRUE, TRUE, FALSE, TRUE)
)

Loop over the columns. For each column, report: - the mean if it is numeric, - the number of TRUE values if it is logical, - the number of different values if it is character.

Hint: is.numeric(), is.logical(), is.character(); sheet[[j]] gets column j as a vector.

for (j in seq_along(sheet)) {
  column <- sheet[[j]]
  if (is.numeric(column)) {
    cat(names(sheet)[j], ": mean", mean(column), "\n")
  } else if (is.logical(column)) {
    cat(names(sheet)[j], ":", sum(column), "TRUE\n")
  } else {
    cat(names(sheet)[j], ":", length(unique(column)), "different values\n")
  }
}
## sample : 4 different values
## rin : mean 7.9 
## reads_m : mean 18.8 
## passed : 3 TRUE

4 Functions

  1. Write a function cells_per_ml() that converts an OD600 value into cells per mL. Use an argument factor with the default value 8e8 (cells/mL per OD unit). Test it on c(0.2, 0.5, 1.1), then with factor = 5e8 for a different species.

cells_per_ml <- function(od, factor = 8e8) {
  od * factor
}
cells_per_ml(c(0.2, 0.5, 1.1))
cells_per_ml(c(0.2, 0.5, 1.1), factor = 5e8)
## [1] 1.6e+08 4.0e+08 8.8e+08
## [1] 1.0e+08 2.5e+08 5.5e+08
  1. Write a function molarity() that calculates the concentration (mol/L) of a solution from the mass of compound (g), its molecular weight (g/mol) and the volume (L). It should stop with a clear error message if the volume is zero or negative. Test it: 5.844 g of NaCl (58.44 g/mol) in 0.5 L should give 0.2 mol/L.

molarity <- function(mass_g, mw, volume_l) {
  if (volume_l <= 0) {
    stop("volume_l must be positive")
  }
  (mass_g / mw) / volume_l
}
molarity(5.844, 58.44, 0.5)
molarity(5.844, 58.44, 0)
## Error in molarity(5.844, 58.44, 0): volume_l must be positive
## [1] 0.2
  1. Write a function replicate_summary() that takes a vector of replicate measurements and returns their mean, standard deviation and coefficient of variation (CV = sd / mean × 100, in %) as a named vector. Add an argument na.rm with the default TRUE and pass it on to mean() and sd(). Test it on the replicates below.
replicates <- c(12.1, 11.8, NA, 12.6, 12.3)

replicate_summary <- function(x, na.rm = TRUE) {
  m <- mean(x, na.rm = na.rm)
  s <- sd(x, na.rm = na.rm)
  c(mean = m, sd = s, cv = s / m * 100)
}
round(replicate_summary(replicates), 2)
replicate_summary(replicates, na.rm = FALSE)
##  mean    sd    cv 
## 12.20  0.34  2.76 
## mean   sd   cv 
##   NA   NA   NA
  1. Turn your loop from exercise 8 into a function describe_columns() that takes any data frame. Test it on sheet, and on the built-in ToothGrowth data set (it has a factor column: what happens to it?).

describe_columns <- function(df) {
  for (j in seq_along(df)) {
    column <- df[[j]]
    if (is.numeric(column)) {
      cat(names(df)[j], ": mean", mean(column), "\n")
    } else if (is.logical(column)) {
      cat(names(df)[j], ":", sum(column), "TRUE\n")
    } else {
      cat(names(df)[j], ":", length(unique(column)), "different values\n")
    }
  }
}
describe_columns(sheet)
describe_columns(ToothGrowth)   # a factor is not numeric or logical, so it ends up in "else"
## sample : 4 different values
## rin : mean 7.9 
## reads_m : mean 18.8 
## passed : 3 TRUE
## len : mean 18.81333 
## supp : 2 different values
## dose : mean 1.166667
  1. Predict the output of each line, then run the code. Explain the result in your journal.
dilution <- 10
make_dilution <- function(conc) {
  dilution <- 100
  conc / dilution
}
make_dilution(500)
dilution

make_dilution(500)   # uses the local dilution = 100
dilution             # still 10: the function's variables stay inside it
## [1] 5
## [1] 10

5 All together

  1. The restriction enzyme DpnI cuts at the site GATC. Write a function count_site(dna, site) that counts how often site occurs in a DNA sequence. Use a for loop over every position, substr() to extract a piece of the same length as site, and if to check whether it matches. Test it on "GATCGATCAAGATC" (3 sites), then make site default to "GATC".

count_site <- function(dna, site = "GATC") {
  n <- 0
  len <- nchar(site)
  for (pos in 1:(nchar(dna) - len + 1)) {
    if (substr(dna, pos, pos + len - 1) == site) {
      n <- n + 1
    }
  }
  n
}
count_site("GATCGATCAAGATC")
count_site("GATCGATCAAGATC", site = "AAG")
## [1] 3
## [1] 1
  1. Use count_site() in a loop to count GATC sites in each of these sequences. Store the results in a named vector. Which sequence has the most sites?
fragments <- c(frag1 = "AAGATCTTGATCCA", frag2 = "GGGCCCAAATTT",
               frag3 = "GATCGATCGATCGA", frag4 = "TTGATCAA")

n_sites <- numeric(length(fragments))
names(n_sites) <- names(fragments)
for (i in seq_along(fragments)) {
  n_sites[i] <- count_site(fragments[i])
}
n_sites
names(n_sites)[n_sites == max(n_sites)]
## frag1 frag2 frag3 frag4 
##     2     0     3     1 
## [1] "frag3"

6 Cheatsheet

Task Code
Loop over values for (x in values) { ... }
Loop over positions for (i in seq_along(x)) { ... }
Create a result vector first result <- numeric(n), character(n)
Loop while a condition holds while (condition) { ... }
Decide if (cond) { ... } else if (cond2) { ... } else { ... }
Decide for a whole vector ifelse(cond, yes, no)
Write a function f <- function(x, y = 1) { ...; result }
Stop with an error stop("message")
Return several values c(a = ..., b = ...) or list(...)
Check a type is.numeric(), is.character(), is.logical()
Time some code system.time({ ... })