← R Programming learning path
R Programming · Module 6 of 10

Functions and control flow

Write reusable functions with conditions and loops.

📖 Key ideas

  1. Define: square <- function(x) { x^2 }.
  2. if/else for decisions; for and while loops.
  3. Vectorised code is usually faster than loops.
  4. apply family: sapply, lapply apply functions to collections.
  5. purrr::map is the tidyverse alternative.
💡 Real-life example: A function is a recipe card you can reuse with different ingredients.
function()Defines a function
sapplyApplies function, simplifies result
lapplyApplies function, returns list
VectorisationOperating on whole vectors