LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 25 lessons

Lesson 2 of 5

Module 1 · R basics

Vectors, functions and loops

Vectors, functions and loops

Vectors, functions and loops

Almost everything in R is a vector. Add functions and loops, and you can already write a small bioinformatics tool: a GC-content calculator for DNA sequences.

⏱ 14 min readModule 1 · R basicsFree
Lesson at a glance4 steps · about 14 min
  1. Types and vectors
  2. Writing a function
  3. Loops and conditions
  4. Missing values

Types and vectors

R has numeric values (120), character text in quotes ("TP53") and logical values (TRUE, FALSE). The function c() combines values into a vector, and maths applies to every element at once.

A type is the kind of value R is holding, and it decides what you can do with it: you can add two numbers, but not two gene names. A vector is an ordered row of values that all share one type, and each value in it is called an element. Even a single number such as 5 is a vector of length one, which is why R printed [1] before every answer in Setting up R and RStudio: the [1] is the position of the first element shown on that line.

If you mix types in one vector, R converts everything to the most flexible type, usually text. For example, c(120, "TP53") becomes two pieces of text, and the 120 can no longer be used in a sum. This is a common reason why a column of numbers read from a spreadsheet will not average: one cell contained a word.

When you are not sure what type an object is, ask R. class(counts) returns "numeric" for the vector below, and class("TP53") returns "character". Checking the type is the first thing to do when a calculation fails with a message about a "non-numeric argument", the same message you met in Setting up R and RStudio when you took the square root of a number in quotes.

R
counts <- c(120, 340, 56, 980)
names(counts) <- c("TP53", "BRCA1", "MYC", "GAPDH")
counts
counts * 2
counts[counts > 100]     # only genes with more than 100 reads

What this does, line by line

  1. counts <- c(120, 340, 56, 980) stores four read counts in one numeric vector.
  2. names(counts) <- c("TP53", "BRCA1", "MYC", "GAPDH") attaches a gene name to each element, in order. The values do not change; each one now carries a label.
  3. counts prints the named vector.
  4. counts * 2 multiplies every element by 2 at once. This is called vectorised arithmetic: one command, applied element by element, with no loop needed.
  5. counts[counts > 100] does two things. The inner part, counts > 100, compares each element with 100 and gives a logical vector: TRUE, TRUE, FALSE, TRUE. Square brackets then keep only the elements where the answer is TRUE. This is called logical indexing.

Square brackets accept other kinds of index too. A number picks by position, so counts[2] gives BRCA1's 340. A name picks by label, so counts["MYC"] gives 56. A minus sign drops a position, so counts[-3] gives every gene except MYC. Positions in R start at 1, not 0 as in some other languages.

Logical tests can be combined. & means "and", | means "or", and ! means "not", so counts[counts > 100 & counts < 500] keeps only TP53 and BRCA1. A frequent slip is to write = where you mean ==: a single equals sign stores or names a value, while the double one asks "are these equal?" and returns TRUE or FALSE.

TP53 BRCA1 MYC GAPDH 120 340 56 980 TP53 BRCA1 MYC GAPDH 240 680 112 1960 TP53 BRCA1 GAPDH 120 340 980

Reading the output. Each result prints as two rows: the names on top and the values beneath. The first block is the stored counts. The second shows every value doubled (120 becomes 240, 980 becomes 1960), still under the same names. The third has only three genes: MYC, with 56 reads, failed the test and was dropped. Because the names travel with the values, you can see at once which genes survived the filter.

Vectors, functions and loops · LSMA free course A named vector of four counts is compared with 100, giving TRUE, TRUE, FALSE, TRUE. Keeping the TRUE positions leaves TP53, BRCA1 and GAPDH. 1 · THE VECTOR 2 · counts > 100 3 · KEEP THE TRUE ONES TP53 BRCA1 MYC GAPDH 120 340 56 980 TRUE TRUE FALSE TRUE TP53 BRCA1 GAPDH 120 340 980 56 is dropped
The test counts > 100 is applied to every element at once and returns one TRUE or FALSE per gene. Square brackets keep the TRUE positions, and the names travel with the values. Schematic, not to scale.

The rules in this lesson, such as how R converts mixed types to the most flexible one (a process called coercion), are set out in R's official manuals, An Introduction to R and The R Language Definition, both written by the R Core Team and free from r-project.org. For a deeper account of vectors, functions and loops, Hadley Wickham's Advanced R (2nd edition, CRC Press, 2019) is the standard book. The manuals describe the current version of R, and details occasionally change between releases, so when an old script behaves differently, check the version notes (the NEWS file) before assuming your code is wrong.

Writing a function

A function takes inputs and returns a result. This one calculates the GC content of a DNA sequence: the share of its bases that are G or C. GC-rich regions behave differently in sequencing and PCR, so it is one of the first things bioinformaticians check.

GC content matters because G and C pair with three hydrogen bonds, while A and T pair with two, so GC-rich DNA holds its two strands together more tightly. Very GC-rich or very AT-rich fragments are copied less evenly by PCR and can end up under-represented in sequencing data. Genomes differ too: the human genome as a whole is about 40% GC, but some regions, such as the CpG islands near many gene starts, are much richer.

A function has three parts: a name you choose, the arguments it accepts (its inputs, here one called seq), and a body between curly brackets that does the work. The value of the last line in the body is what the function returns.

R
gc_content <- function(seq) {
  bases <- strsplit(toupper(seq), "")[[1]]     # split into single letters
  sum(bases %in% c("G", "C")) / length(bases)
}

gc_content("ATGGCGTACGCTTAG")

What this does, line by line

  1. gc_content <- function(seq) { creates a new function and stores it under the name gc_content, exactly as <- stores a number. Inside, the input will be called seq.
  2. toupper(seq) turns the sequence into capital letters, so "atgc" and "ATGC" give the same answer. strsplit(…, "") splits the text at every position, giving single letters. strsplit() returns a list, because it can split several texts at once; [[1]] takes the first (and here the only) element of that list, a plain vector of letters, stored as bases.
  3. bases %in% c("G", "C") asks, for each letter, "is this a G or a C?" and gives TRUE or FALSE. sum() counts the TRUEs, because R treats TRUE as 1 and FALSE as 0. Dividing by length(bases), the number of letters, turns the count into a share between 0 and 1.
  4. The last line calls the function on a 15-letter sequence.

Reading the output. 0.5333333 means that slightly over half the bases, 53.3%, are G or C. R shows seven significant digits; the exact value is 8/15.

Because toupper() runs first, gc_content("atggcgtacgcttag") gives the same 0.5333333. Notice also that bases does not appear in the Environment pane after the function has run. Objects created inside a function exist only while it runs; only the returned value comes back out. This keeps a function from overwriting objects of the same name in your own work.

A function does exactly what its body says, which is not always what you meant. Real sequences often contain N, the code for a base the sequencer could not read. This function counts every N in the length but never as G or C, so gc_content("GCNN") gives 0.5, not 1. Whether that is right depends on your question; if you want the GC share of the readable bases only, you would remove the Ns first. The function also expects one sequence at a time. Given a vector of two, strsplit() splits both but [[1]] keeps only the first, so the second is silently ignored. The next section shows the right way to handle several sequences.

[1] 0.5333333

Worked example · check it by hand

A T G G C G T A C G C T T A G → 15 bases
G: 5   C: 3   → 8 ÷ 15 = 0.533

Always test a new function on an input you can check by hand.

Step by step. Count the letters: A, T, G, G, C, G, T, A, C, G, C, T, T, A, G is 15 bases. The Gs sit at positions 3, 4, 6, 10 and 15, which is 5. The Cs sit at positions 5, 9 and 11, which is 3. Together that is 5 + 3 = 8 G or C bases, and 8 ÷ 15 = 0.5333…, the same as R's answer.

What the answer means. The function agrees with a hand count, so you can trust it on sequences too long to count. Good test inputs include the edge cases: a sequence with no G or C should give 0, and one made only of G and C should give 1. The next code block tries exactly those.

Loops and conditions

A for loop repeats code for each item; if chooses between two paths. cat() prints several values on one line.

A loop is a block of code that runs once for each item in a collection, with a variable that takes each item's value in turn. A condition is a test that gives TRUE or FALSE; if runs one piece of code when the test is TRUE and, with else, another when it is FALSE.

R
seqs <- c(seq1 = "ATGGCGTACGCTTAG", seq2 = "ATATATTTAA", seq3 = "GGCCGCGC")

for (name in names(seqs)) {
  gc <- gc_content(seqs[[name]])
  label <- if (gc > 0.5) "GC-rich" else "AT-rich"
  cat(name, round(gc, 2), label, "\n")
}

sapply(seqs, gc_content)      # the same, without a loop

What this does, line by line

  1. seqs <- c(seq1 = …, seq2 = …, seq3 = …) makes a named character vector of three sequences. Writing name = value inside c() sets the names in one step.
  2. for (name in names(seqs)) { runs the lines inside the curly brackets three times, with name set to "seq1", then "seq2", then "seq3".
  3. seqs[[name]] takes the sequence with that name, and gc_content() calculates its GC share, stored as gc.
  4. if (gc > 0.5) "GC-rich" else "AT-rich" picks one of two labels: "GC-rich" when more than half the bases are G or C, otherwise "AT-rich".
  5. cat(name, round(gc, 2), label, "\n") prints the name, the share rounded to two decimals and the label on one line. "\n" is the code for a new line, so each sequence starts on its own line.
  6. sapply(seqs, gc_content) calls gc_content() on each sequence and returns all three answers as one named vector.
seq1 0.53 GC-rich seq2 0 AT-rich seq3 1 GC-rich seq1 seq2 seq3 0.5333333 0.0000000 1.0000000

Reading the output. The first three lines come from the loop. seq1 is 0.53 and GC-rich, as worked out by hand above. seq2, ATATATTTAA, has no G or C at all, so its share is 0 and it is AT-rich. seq3, GGCCGCGC, is entirely G and C, so its share is 1. The last two lines come from sapply(): the same three numbers, unrounded, under their names. The two edge cases, 0 and 1, give exactly the answers you would expect, which is good evidence that the function is right.

Note the boundary in the condition. gc > 0.5 is FALSE for a sequence of exactly 0.5, so a sequence with equal numbers of GC and AT bases would be labelled "AT-rich". Decide at the start which side a boundary value belongs to, and use >= if you want 0.5 counted as GC-rich. The same choice comes back with every cut-off you set in this course, from read counts to p-values.

sapply() applies a function to every element and collects the answers. R programmers use it, and its relatives, more often than loops.

Its relatives include lapply(), which always returns a list, and vapply(), which also checks that each answer has the type you expect. The loop and sapply() gave the same numbers here; the advantage of sapply() is that it is one short line and returns its results in a form you can store and use, rather than only printing them.

So when is a loop the better choice? Use one when each step depends on the one before, or when the work is a side effect rather than a value, such as reading twenty files or saving one figure per gene. For calculations on every element of a vector, prefer vectorised arithmetic first (counts * 2 needs neither a loop nor sapply()), then sapply() for functions that handle one value at a time. If you do collect results in a loop, create the empty result vector before the loop with the right length, for example numeric(length(seqs)), and fill it by position; growing a vector one element at a time works, but becomes slow on long inputs.

Go deeper: the empty-vector trap in loops

A common way to loop over positions is for (i in 1:length(x)). It works until x is empty. Then length(x) is 0, and 1:0 is not "nothing" but the vector c(1, 0), counting down. The loop runs twice, on positions that do not exist, and gives NA or a confusing error.

seq_along(x) avoids this: it gives 1, 2, 3 and so on, one number per element, and an empty result for an empty vector, so the loop simply does not run. The same trap appears with 1:nrow(df) on a table that a filter has emptied; seq_len(nrow(df)) is the safe version. Empty inputs are rare when you test by hand but common in real pipelines, for example when no gene passes a cut-off.

Missing values

R marks missing data as NA. A calculation that touches an NA returns NA unless you tell it to drop them: mean(c(4, NA, 8)) is NA, while mean(c(4, NA, 8), na.rm = TRUE) is 6.

NA stands for "not available". R refuses to guess: if one value is unknown, the mean of all three is also unknown. The argument na.rm = TRUE means "remove the NAs first", so R averages 4 and 8 and gets (4 + 8) ÷ 2 = 6. Notice that it divides by 2, not 3: the missing value is left out of the count as well as the sum.

Dropping NAs is often reasonable, but always know how many you are dropping. If 4 values out of 10 are missing, a mean of the remaining 6 may no longer describe the whole group. In a sample sheet, a missing treatment label is a question to answer, not a value to ignore, as Cleaning data with dplyr and tidyr shows.

To find out how many values are missing, use is.na(). It returns TRUE for each missing element, so sum(is.na(c(4, NA, 8))) gives 1. You cannot test for NA with ==: NA == NA is itself NA, because R cannot say whether two unknown values are equal. Always use is.na().

Two relatives of NA are worth recognising. NaN, "not a number", is the result of an impossible calculation such as 0 / 0; gc_content("") returns it, because an empty sequence has zero G or C bases out of zero bases. NULL means "nothing at all": not a missing value in a vector, but no vector. In real tables the commonest problem is different again. A spreadsheet cell holding the text "n/a", "-" or a blank space is not NA to R unless you say so when reading the file, and it can turn a whole numeric column into text, the mixing problem from the start of this lesson.

Key point

If you copy and paste the same lines more than twice, write a function. It is shorter, and a fix in one place fixes every use.

Imagine you pasted the GC calculation ten times for ten sequences, then noticed it ignored lower-case letters. You would need to fix ten copies and might miss one. With gc_content(), adding toupper() in one place corrects every call at once.

Further reading · Module 1R for Data Science, 2nd edition: the free book that covers this module and much more. · All reading for this course

Check your understanding

1. What is the GC content of "GGAT" ?

2. What does c(2, 4, 6) * 2 return?

3. What does sapply(x, f) do?

Up next

Lesson 3

Data frames and files

Ask BioTutor

Create a free website with Framer, the website builder loved by startups, designers and agencies.