Skip to content

Alternatives to Loops

A for loop spells out every step of a calculation: take one column, sum it, store the total, move to the next column. For the most common calculations on a matrix, R has a function that does all of those steps in one call, and the apply family and purrr cover most of what remains. Each section below runs one alternative on the same small count matrix. Where a loop does the same work, the section checks that both give the same answer.

The Functions page introduces apply(), sapply(), and lapply(), and it shows how to document a function with a roxygen block.

The matrix holds invented RNA-seq counts for six genes in two control samples and two hypoxia samples. PGK1 and ENO1 are glycolysis genes that hypoxia induces, MKI67 and TOP2A mark dividing cells, and CD19 is a B cell marker with almost no reads. The list gene_sets groups the genes by function. Its B cell set also names MS4A1, a gene that the matrix does not contain.

counts <- matrix(
c(
5210, 4875, 5630, 5402,
1830, 1702, 3920, 4105,
2240, 2390, 4710, 4486,
1310, 1285, 642, 610,
998, 1021, 455, 402,
12, 0, 3, 8
),
nrow = 6,
byrow = TRUE,
dimnames = list(
c("GAPDH", "PGK1", "ENO1", "MKI67", "TOP2A", "CD19"),
c("ctrl_1", "ctrl_2", "hypoxia_1", "hypoxia_2")
)
)
gene_sets <- list(
glycolysis = c("GAPDH", "PGK1", "ENO1"),
proliferation = c("MKI67", "TOP2A"),
b_cell = c("CD19", "MS4A1")
)
counts
ctrl_1 ctrl_2 hypoxia_1 hypoxia_2
GAPDH 5210 4875 5630 5402
PGK1 1830 1702 3920 4105
ENO1 2240 2390 4710 4486
MKI67 1310 1285 642 610
TOP2A 998 1021 455 402
CD19 12 0 3 8

The library size of a sample is the sum of its counts. This loop computes it one column at a time and stores each total in a vector that has its full length before the loop starts.

library_size <- numeric(ncol(counts))
names(library_size) <- colnames(counts)
for (j in seq_len(ncol(counts))) {
library_size[j] <- sum(counts[, j])
}
library_size
ctrl_1 ctrl_2 hypoxia_1 hypoxia_2
11600 11273 15360 15013

colSums() returns the same four totals in one call. all.equal() compares the two results, names included, and returns TRUE when they agree.

colSums(counts)
all.equal(library_size, colSums(counts))
ctrl_1 ctrl_2 hypoxia_1 hypoxia_2
11600 11273 15360 15013
[1] TRUE

rowSums(), colSums(), rowMeans(), and colMeans() cover the summaries that a count matrix needs most often. The genes are rows here, so the row functions return one value per gene and the column functions return one value per sample.

rowSums(counts)
rowMeans(counts)
colMeans(counts)
GAPDH PGK1 ENO1 MKI67 TOP2A CD19
21117 11557 13826 3847 2876 23
GAPDH PGK1 ENO1 MKI67 TOP2A CD19
5279.25 2889.25 3456.50 961.75 719.00 5.75
ctrl_1 ctrl_2 hypoxia_1 hypoxia_2
1933.333 1878.833 2560.000 2502.167

A single NA in a row makes rowMeans() return NA for that gene. Set na.rm = TRUE to average the samples that have a value.

A comparison inside the call turns a sum into a count. counts >= 10 is a logical matrix, and rowSums() adds up its TRUE values, so the result is the number of samples where each gene has at least 10 reads. One more comparison gives a filter that keeps the genes with 10 reads in at least two samples.

rowSums(counts >= 10)
keep <- rowSums(counts >= 10) >= 2
rownames(counts)[keep]
GAPDH PGK1 ENO1 MKI67 TOP2A CD19
4 4 4 4 4 1
[1] "GAPDH" "PGK1" "ENO1" "MKI67" "TOP2A"

CD19 reaches 10 reads in one sample only, so the filter drops it.

Base R has no row function for the standard deviation, so a coefficient of variation per gene needs apply(). With margin 1, apply() passes each row to the function, here the four counts of one gene.

#' Computes the coefficient of variation of one gene.
#'
#' @param gene_counts Numeric vector with the counts of one gene in each
#' sample.
#' @return The standard deviation of the counts divided by their mean.
CoefficientOfVariation <- function(gene_counts) {
sd(gene_counts) / mean(gene_counts)
}
round(apply(counts, 1, CoefficientOfVariation), 3)
GAPDH PGK1 ENO1 MKI67 TOP2A CD19
0.061 0.450 0.383 0.403 0.468 0.924

The standard deviation of GAPDH is 6 percent of its mean. CD19 has the largest value, 0.924, because a change of a few reads is large next to a mean of 5.75 reads.

A function that returns more than one value changes the shape of the result. apply() stores each result as a column, so range() gives a matrix with the genes in columns and the minimum and maximum in rows.

apply(counts, 1, range)
GAPDH PGK1 ENO1 MKI67 TOP2A CD19
[1,] 4875 1702 2240 610 402 0
[2,] 5630 4105 4710 1310 1021 12

t() transposes the result and puts the genes back in rows.

t(apply(counts, 1, range))
[,1] [,2]
GAPDH 4875 5630
PGK1 1702 4105
ENO1 2240 4710
MKI67 610 1310
TOP2A 402 1021
CD19 0 12

sapply() decides the shape of its result from the values that come back. vapply() takes a template of one result as its third argument, FUN.VALUE, and checks every result against it. Here integer(1) declares one integer per gene set.

vapply(gene_sets, length, integer(1))
glycolysis proliferation b_cell
3 2 2

The B cell set has two names, but only CD19 is a row of the matrix. TopGene() keeps the genes of a set that are in the matrix and returns the one with the highest mean count. The counts = counts argument after the template goes to each call of TopGene().

#' Finds the gene of a set with the highest mean count.
#'
#' @param gene_set Character vector of gene symbols. Symbols that are not
#' row names of `counts` are ignored.
#' @param counts Count matrix with genes in rows and samples in columns.
#' @return The symbol of the gene with the highest mean count.
TopGene <- function(gene_set, counts) {
present <- intersect(gene_set, rownames(counts))
set_means <- rowMeans(counts[present, , drop = FALSE])
names(which.max(set_means))
}
vapply(gene_sets, TopGene, character(1), counts = counts)
glycolysis proliferation b_cell
"GAPDH" "MKI67" "CD19"

When the template has the wrong type, vapply() stops at the first result and names the type that it received. tryCatch() catches the error and returns its message, so the script goes on.

type_error <- tryCatch(
vapply(gene_sets, TopGene, numeric(1), counts = counts),
error = \(e) conditionMessage(e)
)
cat(type_error, sep = "\n")
values must be type 'double',
but FUN(X[[1]]) result is type 'character'

sapply() has no template, so it returns the same character vector without an error, and code that expects numbers fails later, further from the cause. vapply() promotes a result along the order logical, integer, double, so an integer result passes a numeric(1) template. It never converts in the other direction.

Map() steps through two or more inputs together and passes the elements at the same position to one function. Scaling counts by size factors has that form, with one column and one factor per sample. The size factor here is the library size of a sample divided by the mean library size. DESeq2 uses a median of ratios instead, and the RNA-seq normalization page explains that method.

size_factors <- colSums(counts) / mean(colSums(counts))
round(size_factors, 3)
ctrl_1 ctrl_2 hypoxia_1 hypoxia_2
0.871 0.847 1.154 1.128

asplit(counts, 2) splits the matrix into a list of its four columns. Map() pairs each column with the factor of the same sample, calls ScaleSample() on each pair, and returns a list named after the samples. Map() is mapply() without the simplification step, so its result is always a list.

#' Divides the counts of one sample by its size factor.
#'
#' @param sample_counts Numeric vector with the counts of one sample.
#' @param size_factor Size factor of the same sample.
#' @return The scaled counts, rounded to one decimal place.
ScaleSample <- function(sample_counts, size_factor) {
round(sample_counts / size_factor, 1)
}
scaled <- Map(ScaleSample, asplit(counts, 2), size_factors)
scaled$hypoxia_1
GAPDH PGK1 ENO1 MKI67 TOP2A CD19
4879.2 3397.2 4081.8 556.4 394.3 2.6

do.call(cbind, scaled) binds the four vectors back into a matrix. For arithmetic of this kind, sweep() gives the same matrix in one vectorized call, and all.equal() confirms it.

scaled_counts <- do.call(cbind, scaled)
scaled_counts
all.equal(scaled_counts, round(sweep(counts, 2, size_factors, "/"), 1))
ctrl_1 ctrl_2 hypoxia_1 hypoxia_2
GAPDH 5978.7 5756.5 4879.2 4789.8
PGK1 2100.0 2009.8 3397.2 3639.8
ENO1 2570.5 2822.2 4081.8 3977.6
MKI67 1503.3 1517.4 556.4 540.9
TOP2A 1145.2 1205.6 394.3 356.4
CD19 13.8 0.0 2.6 7.1
[1] TRUE

purrr gives the same operations one naming scheme. map() always returns a list. map_lgl(), map_int(), map_dbl(), and map_chr() return a vector of the type in their name, and they fail when a result cannot be converted to that type. The \(set) form is the short anonymous function syntax of R 4.1 and later. Use it for one expression, and write a named function for anything longer.

library(purrr)
present_genes <- map(gene_sets, \(set) intersect(set, rownames(counts)))
present_genes
$glycolysis
[1] "GAPDH" "PGK1" "ENO1"
$proliferation
[1] "MKI67" "TOP2A"
$b_cell
[1] "CD19"

MS4A1 is gone from the B cell set. map_int() counts the genes that remain in each set, and map_dbl() averages each set over its genes and all four samples.

map_int(present_genes, length)
round(map_dbl(present_genes, \(set) mean(counts[set, ])), 1)
glycolysis proliferation b_cell
3 2 1
glycolysis proliferation b_cell
3875.0 840.4 5.8

To pass a fixed argument such as the count matrix, write it inside the anonymous function. The purrr reference recommends this form over extra arguments through ..., because it shows which argument belongs to which function.

map_chr(gene_sets, \(set) TopGene(set, counts))
glycolysis proliferation b_cell
"GAPDH" "MKI67" "CD19"

map2_dbl() is the purrr form of Map() for a numeric result. After scaling, each sample has the same total, 13311.5, which is the mean of the four library sizes. This size factor is designed to give that result.

map2_dbl(asplit(counts, 2), size_factors, \(x, s) sum(x / s))
ctrl_1 ctrl_2 hypoxia_1 hypoxia_2
13311.5 13311.5 13311.5 13311.5

A loop fits a calculation where each step needs the result of the step before. The culture below follows logistic growth: each day adds 90 percent of the current count, slowed as the count approaches a capacity of one million cells. Day 3 cannot be computed before day 2.

cells <- numeric(7)
cells[1] <- 2e4
capacity <- 1e6
for (day in seq(2, length(cells))) {
previous <- cells[day - 1]
cells[day] <- previous + 0.9 * previous * (1 - previous / capacity)
}
round(cells)
[1] 20000 37640 70241 129017 230152 389616 603650

Reduce() with accumulate = TRUE and purrr accumulate() return the same seven values, but they still compute one day at a time. The loop states the recurrence line by line, which makes it easier to check against the growth model.

A loop also fits work done for its effect and not for a value, such as one file per sample. purrr has walk() for this case. It calls the function for each element and returns its input invisibly.

out_dir <- file.path(tempdir(), "per_sample")
dir.create(out_dir)
for (sample_id in colnames(counts)) {
sample_table <- data.frame(
gene = rownames(counts),
count = counts[, sample_id]
)
out_file <- file.path(out_dir, paste0(sample_id, ".csv"))
write.csv(sample_table, out_file, row.names = FALSE)
}
list.files(out_dir)
[1] "ctrl_1.csv" "ctrl_2.csv" "hypoxia_1.csv" "hypoxia_2.csv"
Task Function Result
Sum or mean of each row or column rowSums(), colSums(), rowMeans(), colMeans() Named numeric vector
Count of the values that pass a test rowSums(counts >= 10) Named numeric vector
Own function on each row or column apply(x, 1, f), apply(x, 2, f) Vector, or a matrix with one column per row or column of x
One result of a declared type per element vapply(x, f, numeric(1)) Vector of that type
Two inputs in parallel Map(f, x, y) List
One result of any shape per element map(x, f) List
One typed result per element map_int(), map_dbl(), map_chr(), map_lgl() Vector of that type
Two inputs, one number per pair map2_dbl(x, y, f) Double vector
Step that needs the previous result for loop, Reduce(accumulate = TRUE) Vector that the loop fills
Action for each element for loop, walk() Files or other effects

The vapply() type error above is a typical R error, with a message and a call. Debugging & Reading Errors shows how to read both parts, how to find your own code in the stack, and how to catch only the condition that you expect.

The purrr package by Wickham and Henry supplies functional programming tools.

  • purrr map reference

    The reference lists map_vec() and walk() next to the typed map functions. It also explains the .progress argument, which draws a progress bar for a long map.

  • R lapply reference

    The reference defines FUN.VALUE for vapply() and the type promotions that it allows. Read it before you declare a template for a function that can return an integer or a double.

  • R functional programming reference

    The reference covers Map(), Reduce(), and Filter(), including the accumulate argument that reproduces the growth series above.

  • Statistics Globe Hub module “Loops and Their Alternatives in R”

    The module teaches the loop forms and the same alternatives, with exercises on the mtcars data. The Hub overview lists the other modules of the Hub.