Skip to content

Control Flow

Control flow lets your scripts make decisions and repeat actions. These are essential tools for processing biological data. You will use conditionals to filter results and loops to iterate over genes, samples, or files.

Conditionals let your code take different actions based on a test. In bioinformatics, you often check whether a p-value is significant or whether a file exists before reading it.

The if/else statement runs one block of code when a condition is TRUE and another when it is FALSE.

pvalue <- 0.003
if (pvalue < 0.05) {
cat("Result is statistically significant\n")
} else {
cat("Result is not significant\n")
}
Result is statistically significant

The condition inside if() must evaluate to one nonmissing logical value. R raises an error when the condition has more than one element.

You can chain multiple conditions together. This is useful for classifying genes by their fold change direction.

log2fc <- 2.5
if (log2fc > 1) {
cat("Gene is upregulated\n")
} else if (log2fc < -1) {
cat("Gene is downregulated\n")
} else {
cat("No significant change\n")
}
Gene is upregulated

R evaluates conditions from top to bottom. It runs the first block whose condition is TRUE and skips the rest.

Before reading a data file, check that it actually exists. This prevents your script from crashing with a confusing error.

input_file <- "counts.csv"
if (file.exists(input_file)) {
cat("Reading:", input_file, "\n")
} else {
cat("File not found:", input_file, "\n")
}
File not found: counts.csv

This pattern is especially helpful in pipelines where upstream steps may or may not have produced output files.

The if/else statement works on a single value. When you need to apply a condition across an entire vector, use ifelse(). This is the R way to classify every element at once without writing a loop.

pvalues <- c(0.001, 0.23, 0.04, 0.87, 0.005)
significance <- ifelse(pvalues < 0.05, "significant", "not significant")
significance
[1] "significant" "not significant" "significant" "not significant"
[5] "significant"

You can nest ifelse() calls to create three or more categories. Here we classify genes as upregulated, downregulated, or not significant based on log2 fold change.

log2fc_values <- c(2.5, -0.3, -1.8, 0.1, 3.2)
direction <- ifelse(log2fc_values > 1, "up",
ifelse(log2fc_values < -1, "down", "ns"))
direction
[1] "up" "ns" "down" "ns" "up"

Nested ifelse() can become hard to read beyond two or three levels. For more complex cases, consider dplyr::case_when().

A for loop repeats a block of code once for each element in a vector. This is useful when you need to process a list of genes, samples, or files one at a time.

genes <- c("TP53", "BRCA1", "EGFR", "KRAS")
for (gene in genes) {
cat("Processing gene:", gene, "\n")
}
Processing gene: TP53
Processing gene: BRCA1
Processing gene: EGFR
Processing gene: KRAS

Sometimes you need the position of each element, not just its value. Use seq_along() to generate index numbers safely. It handles empty vectors correctly, unlike 1:length(x).

samples <- c("S1", "S2", "S3")
for (i in seq_along(samples)) {
cat("Sample", i, ":", samples[i], "\n")
}
Sample 1 : S1
Sample 2 : S2
Sample 3 : S3

Create a result vector of the required length before this loop. Each iteration then assigns one result to an existing position.

counts <- c(100, 250, 50, 300, 75)
log_counts <- numeric(length(counts))
for (i in seq_along(counts)) {
log_counts[i] <- log2(counts[i] + 1)
}
log_counts
[1] 6.658211 7.971544 5.672425 8.233620 6.247928

The log2() function accepts a vector. It applies the transformation to each element, so this calculation needs no explicit loop.

The loop above can be replaced with a single line:

log_counts_vec <- log2(counts + 1)
log_counts_vec
[1] 6.658211 7.971544 5.672425 8.233620 6.247928

Both forms return the same five values shown here. The vectorized form uses one expression; this example does not measure execution speed.

A loop inside another loop runs in full for each pass of the outer loop. A 96-well plate has rows A to H and columns 1 to 12. The loops below label a smaller plate with 3 rows and 4 columns, so the inner assignment runs 12 times.

plate <- matrix(
"",
nrow = 3,
ncol = 4,
dimnames = list(c("A", "B", "C"), 1:4)
)
for (i in seq_len(nrow(plate))) {
for (j in seq_len(ncol(plate))) {
plate[i, j] <- paste0(rownames(plate)[i], colnames(plate)[j])
}
}
noquote(plate)
1 2 3 4
A A1 A2 A3 A4
B B1 B2 B3 B4
C C1 C2 C3 C4

The work grows with the product of the two lengths. A full 96-well plate takes 96 passes of the inner body, and a loop over 20000 genes inside a loop over the same 20000 genes takes 400 million. For labels like these, outer(rownames(plate), colnames(plate), paste0) builds the same matrix of labels without a loop.

A while loop keeps running as long as its condition is TRUE. This is useful when you do not know in advance how many iterations you need.

Here we simulate how many times a cell population must double to exceed a threshold:

threshold <- 100
current <- 10
doublings <- 0
while (current < threshold) {
current <- current * 2
doublings <- doublings + 1
}
cat("Reached", current, "after", doublings, "doublings\n")
Reached 160 after 4 doublings

Be careful with while loops. If the condition never becomes FALSE, your script will run forever. Always make sure something inside the loop moves toward ending the condition.

A repeat loop has no condition at all. Its body runs until a break stops it, so the test can sit at the end of the body and the body always runs at least once. Here a sample of 5000 cells per microliter is diluted tenfold until it falls below a detection limit of one cell per microliter:

concentration <- 5000
detection_limit <- 1
dilutions <- 0
repeat {
concentration <- concentration / 10
dilutions <- dilutions + 1
if (concentration < detection_limit) {
break
}
}
cat("After", dilutions, "dilutions the sample holds", concentration,
"cells per microliter\n")
After 4 dilutions the sample holds 0.5 cells per microliter

A repeat loop without a reachable break never ends. Put the break test where every pass of the body reaches it.

Inside a loop, next skips to the next iteration and break exits the loop entirely. These are useful for handling missing data or stopping early when a condition is met.

pvalues <- c(0.001, NA, 0.04, 0.5, 0.003)
for (i in seq_along(pvalues)) {
if (is.na(pvalues[i])) {
cat("Skipping NA at position", i, "\n")
next
}
if (pvalues[i] < 0.01) {
cat("Found highly significant result at position", i, "\n")
}
}
Found highly significant result at position 1
Skipping NA at position 2
Found highly significant result at position 5

Use next to skip problematic entries like NA values. Use break when you only need the first match and want to stop searching. The loop below looks for the first gene with a p-value under 0.01 and stops there:

gene_ids <- c("ACTB", "MYC", "TP53", "EGFR", "KRAS")
pvalues <- c(0.2, 0.03, 0.004, 0.001, 0.6)
first_hit <- NA_character_
for (i in seq_along(pvalues)) {
if (pvalues[i] < 0.01) {
first_hit <- gene_ids[i]
break
}
}
first_hit
i
[1] "TP53"
[1] 3

EGFR also passes the test, but the loop never reaches it. After a break, the loop variable keeps its last value, so i tells you where the search stopped. When no element passes, the loop runs to the end and i equals the length of the vector, the same value as a hit in the last position. Test first_hit to know whether the search found a gene.

A vectorized function expresses an operation on a whole vector. For this example, log2(counts + 1) states the calculation directly and removes the explicit index. Speed depends on the function, input, memory use, and R version.

Use a loop when one iteration depends on an earlier result or when each item needs a separate action, such as a file read. Compare performance on the actual workload when speed affects your choice.

The Functions page explains apply(), sapply(), and lapply(). These functions provide other ways to express repeated operations. The Alternatives to Loops page checks row and column summaries, vapply(), Map(), and the purrr map functions against the loops that they replace.

Construct Purpose Example use case
if/else Branch on a single condition Check if a p-value is significant
if/else if/else Branch on multiple conditions Classify a gene as up, down, or unchanged
ifelse() Vectorized conditional Label an entire column of p-values
for Iterate over a vector Process each sample file
Nested for Iterate over every pair of two vectors Label each well of a plate
while Loop until a condition is met Simulate growth until a threshold
repeat Loop until a break Dilute a sample until it is below a limit
next Skip current iteration Skip NA values in a loop
break Exit a loop early Stop after finding the first match

You now know how to make decisions and repeat actions in R. The next page covers how to organize your code into reusable functions. Head to Functions to continue.

  • R control-flow reference

    The reference defines if, for, while, repeat, break, and next. Its argument rules explain the scalar condition required by each branch.

  • An Introduction to R

    The grouping, loops, and conditional execution sections provide longer examples of control flow. Use them to compare explicit count loops with vectorized operations.