1 Introduction

A vector is a sequence of values of the same type, and it is the most basic data structure in R. Most of what you will do in R, from normalising counts to filtering genes, is done with vectors. At the end of this lab you should be able to:

  • create vectors and calculate with them, element by element,
  • predict what happens when vectors of different lengths are combined (recycling),
  • select elements by position, by name and by condition,
  • modify, summarise, count and sort vectors,
  • generate sequences, repeated values, sample names and random samples,
  • store categories as factors and control their order.

1.1 Functions you will need

Task Functions
Create and inspect c(), length(), typeof(), names()
Select x[ ], which()
Summarise mean(), median(), sd(), range(), max(), min(), sum()
Count and sort table(), unique(), sort(), order(), rev()
Generate :, seq(), rep(), paste0(), sample(), rnorm()
Categories factor(), levels()

Use ?function_name to read the help page of any function.

2 Exercises

In all exercises, 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. There are often several equally good solutions.

Keep writing your code and notes in your R Markdown learning journal.

2.1 Create and calculate

You weighed eight mice (in grams) at the start of an experiment and again after four weeks:

weight_start <- c(21.3, 23.8, 19.9, 25.1, 22.4, 24.0, 20.7, 23.3)
weight_end   <- c(22.9, 23.1, 21.5, 27.0, 22.0, 26.2, 22.4, 23.9)
  1. How many mice are there? What type of vector is weight_start? What is the mean starting weight?

length(weight_start)
typeof(weight_start)
mean(weight_start)
## [1] 8
## [1] "double"
## [1] 22.5625
  1. Calculate the weight change of every mouse, and the change in percent of the starting weight. How many vectors (and how many lines of code) did you need?

change <- weight_end - weight_start
change
percent_change <- change / weight_start * 100
round(percent_change, digits = 1)
## [1]  1.6 -0.7  1.6  1.9 -0.4  2.2  1.7  0.6
## [1]  7.5 -2.9  8.0  7.6 -1.8  9.2  8.2  2.6
  1. How many mice lost weight? Use the fact that TRUE counts as 1.

change < 0
sum(change < 0)   # 2 mice
## [1] FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE
## [1] 2
  1. You measured bacterial growth as optical density (OD600) in five cultures. A blank well read 0.05. Subtract the blank from every culture, then convert to cells/mL, assuming 1 OD unit ≈ 8 × 10^8 cells/mL (write it as 8e8).
od <- c(0.45, 0.82, 0.31, 1.10, 0.67)

od_corrected <- od - 0.05     # 0.05 is recycled for every culture
cells_per_ml <- od_corrected * 8e8
cells_per_ml
## [1] 3.20e+08 6.16e+08 2.08e+08 8.40e+08 4.96e+08
  1. Predict the result of each line, then run it. Which one gives a warning, and why?
c(1, 3, 5) + c(2, 4, 6)
c(1, 3, 5, 7) + c(10, 20)
c(1, 3, 5) + c(10, 20)

c(1, 3, 5) + c(2, 4, 6)        # element by element
c(1, 3, 5, 7) + c(10, 20)      # c(10, 20) is recycled to c(10, 20, 10, 20)
c(1, 3, 5) + c(10, 20)         # warning: 3 is not a multiple of 2
## Warning in c(1, 3, 5) + c(10, 20): longer object length is not a multiple of
## shorter object length
## [1]  3  7 11
## [1] 11 23 15 27
## [1] 11 23 15

2.2 Select elements

The first eight amino acids of a protein:

protein <- c("Met", "Ala", "Gly", "Leu", "Ser", "Lys", "Pro", "Trp")
  1. Select:
    • the third amino acid,
    • the first and the last (without typing the number 8),
    • amino acids 2 to 5,
    • all except the first (the start methionine).
    What do you get with protein[20]?

protein[3]
protein[c(1, length(protein))]
protein[2:5]
protein[-1]
protein[20]   # NA: there is no 20th element
## [1] "Gly"
## [1] "Met" "Trp"
## [1] "Ala" "Gly" "Leu" "Ser"
## [1] "Ala" "Gly" "Leu" "Ser" "Lys" "Pro" "Trp"
## [1] NA
  1. Give the mouse weights the names "M1", "M2", …, "M8" (without typing all of them). Then extract the starting weights of mice M3 and M7 by name.

names(weight_start) <- paste0("M", 1:8)
weight_start
weight_start[c("M3", "M7")]
##   M1   M2   M3   M4   M5   M6   M7   M8 
## 21.3 23.8 19.9 25.1 22.4 24.0 20.7 23.3 
##   M3   M7 
## 19.9 20.7
  1. Which mice weighed more than 23 g at the start? Give their weights, their names and their positions. How many mice weighed between 21 and 24 g?

weight_start[weight_start > 23]
names(weight_start)[weight_start > 23]
which(weight_start > 23)
sum(weight_start > 21 & weight_start < 24)
##   M2   M4   M6   M8 
## 23.8 25.1 24.0 23.3 
## [1] "M2" "M4" "M6" "M8"
## M2 M4 M6 M8 
##  2  4  6  8 
## [1] 4

2.3 Modify and summarise

  1. You discover that the scale was not calibrated when M5 was weighed. Replace its starting weight with NA. Then add a ninth mouse, M9, that weighed 22.8 g.

weight_start["M5"] <- NA
weight_start <- c(weight_start, M9 = 22.8)
weight_start
##   M1   M2   M3   M4   M5   M6   M7   M8   M9 
## 21.3 23.8 19.9 25.1   NA 24.0 20.7 23.3 22.8
  1. Calculate the mean, median, standard deviation and range of weight_start. Which mouse was the heaviest? (Hint: ?which.max.)

mean(weight_start, na.rm = TRUE)
median(weight_start, na.rm = TRUE)
sd(weight_start, na.rm = TRUE)
range(weight_start, na.rm = TRUE)
names(which.max(weight_start))
## [1] 22.6125
## [1] 23.05
## [1] 1.803518
## [1] 19.9 25.1
## [1] "M4"
  1. A colleague types "missing" instead of NA for mouse M2. What happens to the vector? What happens when you calculate the mean?

weight_bad <- weight_start
weight_bad["M2"] <- "missing"
weight_bad                      # every value is now text!
typeof(weight_bad)
mean(weight_bad, na.rm = TRUE)  # warning and NA: you cannot average text
## Warning in mean.default(weight_bad, na.rm = TRUE): argument is not numeric or
## logical: returning NA
##        M1        M2        M3        M4        M5        M6        M7        M8 
##    "21.3" "missing"    "19.9"    "25.1"        NA      "24"    "20.7"    "23.3" 
##        M9 
##    "22.8" 
## [1] "character"
## [1] NA

2.4 Count and sort

The blood groups of 20 blood donors:

blood <- c("O", "A", "A", "B", "O", "AB", "O", "A", "O", "B",
           "A", "O", "O", "A", "B", "O", "A", "AB", "O", "A")
  1. Which blood groups occur? How many donors have each group, and what proportion is that? Which group is the most common?

unique(blood)
table(blood)
table(blood) / length(blood)
names(which.max(table(blood)))
## [1] "O"  "A"  "B"  "AB"
## blood
##  A AB  B  O 
##  7  2  3  8 
## blood
##    A   AB    B    O 
## 0.35 0.10 0.15 0.40 
## [1] "O"
  1. Sort the mouse starting weights from heaviest to lightest. Then give the names of the three heaviest mice. What happened to the NA?

sort(weight_start, decreasing = TRUE)               # NA is dropped
names(sort(weight_start, decreasing = TRUE))[1:3]
# or, with order():
names(weight_start)[order(weight_start, decreasing = TRUE)][1:3]
##   M4   M6   M2   M8   M9   M1   M7   M3 
## 25.1 24.0 23.8 23.3 22.8 21.3 20.7 19.9 
## [1] "M4" "M6" "M2"
## [1] "M4" "M6" "M2"

2.5 Generate vectors

  1. Create:
    • sampling time points every 12 hours from 0 to 48 hours,
    • the sample names "WT_rep1", "WT_rep2", "WT_rep3", "KO_rep1", "KO_rep2", "KO_rep3",
    • all 96 well names of a plate, from "A1" to "H12". (Hint: LETTERS holds the alphabet.)

seq(from = 0, to = 48, by = 12)
paste0(rep(c("WT", "KO"), each = 3), "_rep", 1:3)   # 1:3 is recycled!
wells <- paste0(rep(LETTERS[1:8], each = 12), 1:12)
length(wells)
head(wells, 14)
## [1]  0 12 24 36 48
## [1] "WT_rep1" "WT_rep2" "WT_rep3" "KO_rep1" "KO_rep2" "KO_rep3"
## [1] 96
##  [1] "A1"  "A2"  "A3"  "A4"  "A5"  "A6"  "A7"  "A8"  "A9"  "A10" "A11" "A12"
## [13] "B1"  "B2"
  1. Join all eight amino acids of protein into a single string, separated by "-".

paste(protein, collapse = "-")
## [1] "Met-Ala-Gly-Leu-Ser-Lys-Pro-Trp"

2.6 Random sampling

  1. You have 12 patients, "P01" to "P12". Randomly choose 4 of them for a pilot study. Use set.seed(2026) first and compare your answer with your neighbour. Why do you get the same result?

patients <- sprintf("P%02d", 1:12)   # %02d pads numbers with a leading zero
set.seed(2026)
sample(patients, size = 4)
## [1] "P09" "P01" "P06" "P04"
  1. Simulate 100 offspring of an Aa × Aa cross, where the genotypes AA, Aa and aa are expected in a 1:2:1 ratio. Count the genotypes. How close are they to the expected 25, 50 and 25? Try again with 1,000 offspring.

offspring <- sample(c("AA", "Aa", "aa"), size = 100, replace = TRUE,
                    prob = c(0.25, 0.5, 0.25))
table(offspring)

offspring_big <- sample(c("AA", "Aa", "aa"), size = 1000, replace = TRUE,
                        prob = c(0.25, 0.5, 0.25))
table(offspring_big) / 1000
## offspring
## aa Aa AA 
## 23 55 22 
## offspring_big
##    aa    Aa    AA 
## 0.271 0.484 0.245
  1. Simulate the heights of 100 adults with rnorm(), using a mean of 170 cm and a standard deviation of 10 cm. How many are taller than 190 cm? What are the mean and standard deviation of your simulated heights?

heights <- rnorm(100, mean = 170, sd = 10)
sum(heights > 190)
mean(heights)
sd(heights)
## [1] 2
## [1] 170.0652
## [1] 8.756789

2.7 Factors

  1. Store the tissue types of these biopsies as a factor. What are its levels, and how many biopsies are there of each type? Then change the order of the levels so that "healthy" comes first.
tissue <- c("tumour", "healthy", "tumour", "inflamed", "healthy", "tumour")

tissue <- factor(tissue)
levels(tissue)      # alphabetical
table(tissue)
tissue <- factor(tissue, levels = c("healthy", "inflamed", "tumour"))
levels(tissue)
## [1] "healthy"  "inflamed" "tumour"  
## tissue
##  healthy inflamed   tumour 
##        2        1        3 
## [1] "healthy"  "inflamed" "tumour"
  1. Pain was scored as "none", "mild", "moderate" or "severe". Create an ordered factor from the scores below. How many patients had more than mild pain? What was the most severe score?
pain <- c("mild", "none", "severe", "moderate", "mild", "moderate", "none")

pain <- factor(pain, levels = c("none", "mild", "moderate", "severe"),
               ordered = TRUE)
pain
sum(pain > "mild")
max(pain)
## [1] mild     none     severe   moderate mild     moderate none    
## Levels: none < mild < moderate < severe
## [1] 3
## [1] severe
## Levels: none < mild < moderate < severe
  1. A factor trap. Drug doses were read in as a factor. Convert them to numbers with as.numeric(). What went wrong, and how can you fix it?
dose <- factor(c("10", "5", "20", "5", "10"))

as.numeric(dose)                 # wrong! these are the level codes 1, 2, 3
levels(dose)                     # levels are sorted as text: "10" "20" "5"
as.numeric(as.character(dose))   # convert to text first, then to numbers
## [1] 1 3 2 3 1
## [1] "10" "20" "5" 
## [1] 10  5 20  5 10