class: center, middle, inverse, title-slide .title[ # Replication, Control Structures & Functions ] .author[ ### Guilherme Dias ] --- exclude: true count: false <link href="https://fonts.googleapis.com/css?family=Roboto|Source+Sans+Pro:300,400,600|Ubuntu+Mono&subset=latin-ext" rel="stylesheet"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous"> --- name: protocol # You already write programs 🧪 A protocol from the lab bench: ``` For each of the 12 cultures: measure the OD600 if OD600 > 0.6: harvest the cells otherwise: back in the incubator Then do a miniprep (see protocol 3) ``` -- .pull-left-50[ <br> | Protocol | R | |:---------|:--| | "For each…" | `for` loop | | "If… otherwise…" | `if` / `else` | | "See protocol 3" | a **function** | ] .pull-right-50[ <br><br> ### Today: write them in R. ] --- name: for_loop # 🔁 The `for` loop Repeat the same steps for every element: ``` r samples <- c("S1", "S2", "S3") for (sample in samples) { print(paste("Processing", sample)) } ``` ``` ## [1] "Processing S1" ## [1] "Processing S2" ## [1] "Processing S3" ``` -- ``` for (variable in vector) { code that uses variable } ``` `sample` takes each value of `samples` in turn. --- name: for_index # Looping with an index Use `seq_along()` to loop over **positions**. Handy when you need two vectors at once: ``` r od <- c(0.42, 0.71, 0.65) for (i in seq_along(samples)) { cat(samples[i], "has OD600", od[i], "\n") } seq_along(samples) ``` ``` ## S1 has OD600 0.42 ## S2 has OD600 0.71 ## S3 has OD600 0.65 ## [1] 1 2 3 ``` .footnote[`seq_along(x)` is safer than `1:length(x)`: it also works when `x` is empty.] --- name: for_store # Storing results Create the result vector **before** the loop, then fill it in: ``` r cells <- numeric(length(od)) # 3 empty slots for (i in seq_along(od)) { cells[i] <- od[i] * 8e8 # cells/mL (approx.) } cells ``` ``` ## [1] 3.36e+08 5.68e+08 5.20e+08 ``` -- .content-box-yellow[ Avoid `result <- c(result, new)` in a loop: R copies the vector every time. Fine for 10 elements, painfully slow for 100,000. ] --- name: vectorise # Do you even need a loop? Most R functions work on whole vectors: ``` r od * 8e8 # same result, no loop ``` ``` ## [1] 3.36e+08 5.68e+08 5.20e+08 ``` -- **Use a vectorised function when one exists:** `sum()`, `mean()`, `rowSums()`, `colMeans()`, `log2()`, `paste0()`, … **Use a loop when** each step depends on the previous one, or a step is too complex for one function call. --- name: while_loop # 🔁 The `while` loop Repeat **as long as** a condition is `TRUE`. Useful when you don't know how many steps you need. How many 1:10 dilutions until a 2,000 ng/µL stock is below 1 ng/µL? ``` r conc <- 2000 n_dilutions <- 0 while (conc >= 1) { conc <- conc / 10 n_dilutions <- n_dilutions + 1 } n_dilutions conc ``` ``` ## [1] 4 ## [1] 0.2 ``` .footnote[Make sure the condition becomes `FALSE` eventually, or the loop runs forever. **Esc** (or the red stop sign in RStudio) stops it.] --- name: if # 🔀 Decisions: `if` Run code only **if** a condition is `TRUE`: ``` r od_culture <- 0.71 if (od_culture > 0.6) { print("Harvest!") } ``` ``` ## [1] "Harvest!" ``` -- ``` if (condition) { code } ``` The condition must be **one** `TRUE` or `FALSE`. --- name: if_else # `if` … `else` Two options: ``` r for (i in seq_along(od)) { if (od[i] > 0.6) { cat(samples[i], ": harvest\n") } else { cat(samples[i], ": back to the incubator\n") } } ``` ``` ## S1 : back to the incubator ## S2 : harvest ## S3 : harvest ``` --- name: else_if # More than two options: `else if` RNA integrity number (RIN): is the RNA good enough to sequence? ``` r rin <- 6.8 if (rin >= 8) { "good" } else if (rin >= 6) { "use with care" } else { "degraded" } ``` ``` ## [1] "use with care" ``` R checks the conditions **in order** and runs the first one that is `TRUE`. --- name: ifelse # `if` vs. `ifelse()` `if` needs **one** `TRUE`/`FALSE`. With a vector: ``` r if (od > 0.6) print("Harvest!") ``` ``` ## Error in if (od > 0.6) print("Harvest!"): the condition has length > 1 ``` -- `ifelse()` is the **vectorised** version: ``` r ifelse(od > 0.6, "harvest", "incubate") ``` ``` ## [1] "incubate" "harvest" "harvest" ``` --- name: functions # 📦 Functions Package code you use again and again. Dilution with C1 × V1 = C2 × V2: ``` r stock_volume <- function(stock_conc, target_conc, final_volume) { volume <- target_conc * final_volume / stock_conc return(volume) } stock_volume(250, 10, 20) # µL of stock for 20 µL at 10 ng/µL ``` ``` ## [1] 0.8 ``` -- ``` name <- function(argument1, argument2) { code return(result) } ``` Write it once. Use it everywhere. Fix a bug in one place. --- name: fn_args # Arguments: names and defaults Give arguments **default values**, and call them **by name**: ``` r stock_volume <- function(stock_conc, target_conc, final_volume = 20) { target_conc * final_volume / stock_conc } stock_volume(250, 10) # uses final_volume = 20 stock_volume(250, 10, final_volume = 50) stock_volume(target_conc = 10, stock_conc = 250) # any order, by name ``` ``` ## [1] 0.8 ## [1] 2 ## [1] 0.8 ``` .footnote[Without `return()`, a function returns its last value.] --- name: fn_check # Check the input Stop with a clear message instead of returning nonsense: ``` r stock_volume <- function(stock_conc, target_conc, final_volume = 20) { if (target_conc > stock_conc) { stop("The target can't be more concentrated than the stock!") } target_conc * final_volume / stock_conc } stock_volume(5, 10) ``` ``` ## Error in stock_volume(5, 10): The target can't be more concentrated than the stock! ``` --- name: fn_return # Returning more than one value Return a **named vector** (or a list): ``` r dilution_plan <- function(stock_conc, target_conc, final_volume = 20) { stock <- target_conc * final_volume / stock_conc c(stock = stock, water = final_volume - stock) } plan <- dilution_plan(250, 10) plan plan["water"] ``` ``` ## stock water ## 0.8 19.2 ## water ## 19.2 ``` --- name: scope # What happens inside, stays inside ``` r myfunction <- function() { age <- 5 # local variable } print(age) ``` ``` ## [1] 70 ``` -- - Variables created inside a function **disappear** when it finishes. - Pass everything a function needs as **arguments**, and get results back with `return()`. --- name: together # All together: find the stop codon 🧬 ``` r first_stop <- function(dna) { stops <- c("TAA", "TAG", "TGA") for (pos in seq(1, nchar(dna) - 2, by = 3)) { # cycle every codon codon <- substr(dna, pos, pos + 2) if (codon %in% stops) { return(pos) # stop at the first stop codon } } return(NA) # if no stop codon is found, return NA } first_stop("ATGGCCTTGCATTAGGCA") first_stop("ATGGCC") ``` ``` ## [1] 13 ## [1] NA ``` A function, a loop and a decision: a tiny genome annotation tool. --- name: recap # Recap | | Use it to | Example | |:--|:----------|:--------| | 🔁 `for` | repeat for each element | `for (i in seq_along(x)) { ... }` | | 🔁 `while` | repeat until a condition fails | `while (conc >= 1) { ... }` | | 🔀 `if` / `else` | choose what to do | `if (od > 0.6) { ... } else { ... }` | | 🔀 `ifelse()` | choose for a whole vector | `ifelse(od > 0.6, "yes", "no")` | | 📦 `function` | package code for reuse | `f <- function(x, y = 1) { ... }` | <br> **Remember:** - Vectorise first. Loop when you must. - Create the result **before** the loop. - Small functions, clear names, test on input where you know the answer. <!-- --------------------- Do not edit this and below --------------------- --> --- name: end_slide class: end-slide, middle count: false # See you at the next lecture! .end-text[ <p class="smaller"> <span class="small" style="line-height: 1.2;">Graphics from </span><img src="./assets/freepik.jpg" style="max-height:20px; vertical-align:middle;"><br> Created: 12-Nov-2026 • <a href="https://www.scilifelab.se/">SciLifeLab</a> • <a href="https://nbis.se/">NBIS</a> </p> ]