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
Section titled “Conditionals”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.
if/else
Section titled “if/else”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 significantThe condition inside if() must evaluate to one nonmissing logical value. R raises an error when the condition has more than one element.
if/else if/else
Section titled “if/else if/else”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 upregulatedR evaluates conditions from top to bottom. It runs the first block whose condition is TRUE and skips the rest.
Checking file existence
Section titled “Checking file existence”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.csvThis pattern is especially helpful in pipelines where upstream steps may or may not have produced output files.
Vectorized ifelse()
Section titled “Vectorized ifelse()”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().
For loops
Section titled “For loops”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: TP53Processing gene: BRCA1Processing gene: EGFRProcessing gene: KRASLooping with an index
Section titled “Looping with an index”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 : S1Sample 2 : S2Sample 3 : S3Collecting results in a loop
Section titled “Collecting results in a loop”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.247928Vectorized alternative
Section titled “Vectorized alternative”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.247928Both forms return the same five values shown here. The vectorized form uses one expression; this example does not measure execution speed.
Nested loops
Section titled “Nested loops”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 4A A1 A2 A3 A4B B1 B2 B3 B4C C1 C2 C3 C4The 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.
While loops
Section titled “While loops”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 <- 100current <- 10doublings <- 0
while (current < threshold) { current <- current * 2 doublings <- doublings + 1}cat("Reached", current, "after", doublings, "doublings\n")Reached 160 after 4 doublingsBe 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.
Repeat loops
Section titled “Repeat loops”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 <- 5000detection_limit <- 1dilutions <- 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 microliterA repeat loop without a reachable break never ends. Put the break test where every pass of the body reaches it.
next and break
Section titled “next and break”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 1Skipping NA at position 2Found highly significant result at position 5Use 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_hiti[1] "TP53"[1] 3EGFR 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.
Choose an operation for the calculation
Section titled “Choose an operation for the calculation”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.
Quick reference
Section titled “Quick reference”| 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 |
Next steps
Section titled “Next steps”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.
Further reading
Section titled “Further reading”-
The reference defines if, for, while, repeat, break, and next. Its argument rules explain the scalar condition required by each branch.
-
The grouping, loops, and conditional execution sections provide longer examples of control flow. Use them to compare explicit count loops with vectorized operations.