Day 3 – From repetition to algorithms

Learning goals

By the end of this day, you should be able to:

  • explain what an algorithm is and why formalizing steps is important
  • read and write simple pseudocode to plan a solution
  • understand core data types in R (numeric, character, logical, etc.) including how R handles missing values
  • use common data structures in R (vectors, matrices, data frames, lists) and understand their differences
  • write basic R code with loops (for, while) and conditional statements (if)
  • create and use your own functions in R to automate tasks
  • import and use packages in R, understanding the role of the R ecosystem

No prior programming experience is assumed, though familiarity with R basics from Day 2 will help.


Motivation

Programming allows us to express repetitive or complex tasks as a clear set of instructions – an algorithm – so the computer can execute them quickly and consistently. Just as a recipe guides a cook through steps to bake a cake, an algorithm guides the computer through steps to solve a problem. Today, we’ll demystify programming by starting with simple logic and gradually building up to writing our own small functions in R. The goal isn’t to turn you into software engineers overnight, but to show how a little coding can save a lot of time and prevent errors.


Agenda

13:30–14:15 | Block 1 – Algorithms and pseudocode
- Why we need algorithms: replacing repetitive manual work with clear instructions
- Algorithms in everyday life (recipes, protocols)
- Writing pseudocode: planning a solution in plain language
- Flow of logic: sequence, decisions (if/else), repetition (loops)
- Example: pseudocode for a simple data cleaning task

14:15–14:30 | Break ☕️

14:30–15:15 | Block 2 – Programming basics in R
- Core data types in R: numeric, integer, character, logical; special values (NA, NaN, Inf, NULL)
- Data structures: vectors (atomic vectors), matrices/arrays, lists, data frames (tibbles)
- Indexing and subsetting data (extracting elements by position or name)
- Vectorized operations in R (working with whole sets of values at once)
- Loops (for loops to iterate; if statements for branching)
- Comparing vectorization vs looping in R with examples

15:15–15:30 | Break ☕️

15:30–16:15 | Block 3 – Functions and tooling in R
- Using built-in functions and understanding function arguments
- Writing your own functions (syntax: function(name) { body })
- Function examples: a simple conversion or calculation
- Debugging basics: reading error messages, using print() for insight
- The R ecosystem: packages and libraries (using install.packages and library to extend R’s capabilities)
- Example: using a package (e.g., ggplot2 or readr) to illustrate how community-contributed tools enhance productivity
- (Optional) Brief mention of RStudio features for coding (autocomplete, help pane)

16:15–16:30 | Reflection, discussion, and outlook 🧠
- What concept was most challenging, and how might you get more practice?
- Can you identify a repetitive task in your work that could be turned into an algorithm?
- What would you like to automate or improve with programming going forward?
- Preview of Day 4: cleaning data and ensuring reproducibility with code


From manual steps to algorithms

Using R effectively means learning to think like a programmer, which starts with understanding algorithms and logic.

Algorithm is a step-by-step procedure to accomplish a task. It’s like a cooking recipe: a clear sequence of instructions that leads to a desired outcome. In data analysis, an algorithm could be something like: “For each observation, if the value is negative, mark it as an outlier; otherwise include it in the summary.”

Writing out an algorithm forces you to be precise about what needs to be done – and in what order. Even sorting a list of numbers or calculating a summary statistic involves an algorithm (either one you write, or one built into a software tool).

What R is

R is a tool to store things (numbers, text, tables) in objects, and then ask questions about them (summaries, plots, comparisons) or transform them.

# The arrow means: store the value on the right into the name on the left
x <- 5
x

Thinking in algorithms: a simple example

Let’s say we want to compute the average (mean) of a list of numbers without using a built-in formula: 1. Take a list of numbers (our input). 2. Set a counter count to 0 and a sum to 0. 3. For each number in the list: add it to sum and add 1 to count. 4. After the loop, compute average = sum / count. 5. Output the average.

This is an algorithm for the mean. It’s conceptually what the formula does, but written as explicit steps. We could write it in plain English, as above, or in a structured

pseudocode:
Pseudocode: Calculate Mean

initialize sum = 0 
initialize count = 0 
for each value in the list: 
  sum = sum + value 
  count = count + 1 
if count is 0: 
    return "No data" // avoid division by zero 
else: 
    mean = sum / count 
  
  return mean

Even if you never coded before, this pseudocode is understandable. It’s essentially how you would explain the process to someone else. The computer, however, needs it in a more formal language (like R). But writing pseudocode first helps clarify your logic before worrying about R syntax.

Tip

Tip: When tackling a programming task, it often helps to write out the steps in pseudocode or plain language first. This separates the problem-solving from the syntax. Once the steps make sense, you can translate them into code.

Control flow: sequence, selection, repetition

Algorithms often involve:

  • Sequence: executing instructions in order.
  • Selection (branching): making decisions (if X is true, do this, otherwise do that).
  • Repetition: doing something multiple times (looping).

In our mean calculation example:

  • Sequence: we had steps to follow one after another.
  • Selection: we used an if to check if count is 0 at the end.
  • Repetition: the “for each value” part is a loop.

Another everyday example – a protocol for labeling samples:

For each collected sample:

if sample has a barcode:

scan the barcode 

else:

assign a temporary ID and record it

This algorithm loops over each sample (repetition) and does one of two things depending on a condition (selection). Thinking algorithmically is largely about breaking problems into these logical components.


Data types and structures in R

Now let’s bring these ideas into R. Programming in R (or any language) requires understanding how the language represents data and what operations it provides.

Atomic data types in R

R has a few atomic data types (the simplest building blocks), this :

  • Numeric: for numbers (real numbers). Example: 42, 3.14. (R by default treats numbers as double-precision floats.)
class(10.1) #asks: How should R treat this conceptually?
#response: "numeric"
typeof(10.1) #asks: How is this stored in memory?
#response: "double"
  • Integer: for integer numbers. Example: 42L (the L suffix denotes an integer in R, though usually R will convert to numeric if not specified).
  • Character: for text strings. Example: "Hello world", "Panthera onca" (species name).
  • Logical (Boolean): for TRUE/FALSE values. Example: TRUE, FALSE. (Often the result of comparisons like 5 > 3 yields TRUE.)
  • Factor: a special type for categorical data (underlyingly stored as integers with labels).
  • Complex (for complex numbers) and Raw (for raw bytes) exist, but are rarely used in typical data analysis.

🚀💥💶💩 European Space Agency’s Ariane 5 rocket failure

why it matters to learn about data types

  • Launch date: 4 June 1996
  • Failure time: 37 seconds after liftoff
  • Cost: ≈ €370 million
  • Cause: numeric overflow
  • Trigger: conversion of a 64-bit floating-point value to a 16-bit signed integer
  • Why it happened: code reused from Ariane 4, where this value could never exceed the integer range
  • Result: inertial reference system shut down, guidance lost, automatic self-destruction

Note

What “double” actually means

A double-precision number is stored as:

  • 1 bit: sign (positive or negative)
  • 11 bits: exponent (how big or small the number is)
  • 52 bits: mantissa (the significant digits)

So internally, a number looks like:

± (significant digits) × 2^(exponent)

Base 2, not base 10. That detail matters more than people expect. Because numbers are stored in binary, many decimal values cannot be represented exactly.

Example:

0.1 + 0.2 == 0.3
[1] FALSE

returns FALSE in R.

This is not a bug, it’s binary arithmetic. What the computer actually stores is closer to:

0.30000000000000004

Usually harmless. Occasionally disastrous. Always worth remembering.

Real world: climate and biodiversity models accumulating rounding error over thousands of iterations.

The blunt distinction (with ranges)

Aspect numeric integer
Storage double precision float 32-bit integer
Range approx ±1.8 × 10³⁰⁸ −2,147,483,648 to 2,147,483,647
Decimal points allowed not allowed
Exact representation often approximate exact (within range)
Default type yes no
Memory 8 bytes 4 bytes
Class "numeric" "integer"

Two clarifications worth remembering

Range ≠ precision
Numerics can be astronomically large or tiny, but only about 15–16 decimal digits are reliable.
Integers are exact, but brutally finite.

Integers fail loudly, numerics fail quietly
Exceed the integer range and you get NA with a warning.
Push doubles too far and you get rounding, overflow to Inf, or underflow to zero. No warning.

#One-line R demo (integer overflow)**  
.Machine$integer.max+0L
#precision double
1.00000000001-1
1.00000000000001-1
1.000000000000001-1
1.0000000000000001-1

R also has some special values:

  • NA: “Not Available,” a missing value placeholder. There are NA versions for each type (numeric NA, character NA, etc., but usually just NA works and propagates appropriately).
  • NaN: “Not a Number,” a result of undefined mathematical operations (like 0/0). It’s a type of numeric NA.
  • Inf and -Inf: positive or negative infinity (like the result of 1/0 or -1/0).
  • NULL: represents the absence of any value or object (different from NA which is an element in a vector; NULL is often used to indicate “nothing” as an object or list element).

Understanding types matters because operations behave differently depending on type. For instance, adding two numbers is fine, but adding a number to a string results in an error. R will also sometimes coerce types in a vector (e.g., mixing numbers and text in the same vector will turn all into text).

Data structures in R

Beyond single values, we have data structures to hold collections of values:

  • Vector: the most basic container, holding a sequence of values of the same type. A vector can be numeric, character, logical, etc. You can create one with c(), e.g. weights <- c(2.4, 5.1, 3.3) which is a numeric vector of length 3.
  • Matrix: a 2D arrangement of values (like a table of one type, essentially a vector with dimensions). All entries in a matrix must also be of the same type. You can make a matrix with matrix() or by dimming a vector.
  • Array: similar to a matrix but can have more than 2 dimensions (e.g., a 3D array).
  • Data frame: a table where each column can be a different type. This is like a spreadsheet or CSV file read into R – the most common structure for datasets. Columns are vectors of equal length. For example, a data frame df might have one numeric column height, one character column species, etc. Each row represents an observation.
  • List: a flexible container that can hold a collection of items of possibly different types and sizes. Lists are extremely useful in R because many complex objects (models, results) are stored as lists. You can think of a list as a general toolbox – each element can be anything (a vector, a data frame, another list, …). Create with list() function, e.g., my_list <- list(name="Alice", scores=c(90,95,88), info=data.frame(age=30, dept="Biology")). Lists don’t require all elements to be same length or type.

For the Belize data, we’ve mainly used data frames (for tables of observations). Under the hood, a data frame is actually a list of equal-length vectors (each column is a vector).

Being comfortable with vectors and data frames is key: - To access elements of a vector, use square brackets. weights[2] gives the second element of weights. - Data frames can be accessed with either df$column_name (to get a column as a vector) or df[row, column] indexing. For instance, df[5, "species"] would give the species of the 5th observation.

Recall from last week: R basics

Before we continue, let’s quickly test what we learned form the operators and revisit how we can read data into R directly from the internet.

url <- "https://raw.githubusercontent.com/ohagen/course_DigitalCompetenceInTheBiologicalSciences/refs/heads/main/data/raw/csv/dist_day02_sep_semicolon__dec_comma.csv"

dest <- "dist_day02.csv"

download.file(url, dest, mode = "wb")

mytable <- read.csv(dest, sep = ";", dec = ",")

# see structure and type of data
str(mytable)

# see the top 6 rows... could be also mytable[1:6,]
head(mytable)

# do summary statistics
summary(mytable)

# histogram of a column
hist(mytable$A)

#boxplot
boxplot(mytable)

Example: dealing with missing values

Suppose we have a numeric vector of tree diameters and some are missing:

diameters <- c(10.4, 8.1, NA, 9.5, 6.8)

The length(diameters) is 5, but one is NA. If we do mean(diameters), as noted, we get NA because by default R can’t compute the mean if any value is missing. We must do mean(diameters, na.rm = TRUE) to remove NAs in the calculation. We could also find which entries are missing by is.na(diameters) which returns a logical vector: FALSE FALSE TRUE FALSE FALSE in this case. We can use that to our advantage to filter or replace missing values. For instance, to filter out missing: clean_diameters <- diameters[ ! is.na(diameters) ] Here ! is “not”, so !is.na(diameters) is TRUE for entries that are not NA, and we index the vector with that logical vector to keep only the non-missing values. This combination of vector operations and logical conditions is very powerful for data cleaning – you can pick out elements meeting certain criteria without writing an explicit loop.

Vectorized thinking versus loops

R is optimized to work with vectors. Many operations you might think of doing with a loop can be done in one go. For example, if we have two numeric vectors x and y of the same length, doing x + y will automatically add element by element (no loop needed in R code – it loops internally in C, which is faster). This is vectorization. Similarly, if we have a vector of temperatures in Celsius and want to convert to Fahrenheit, we can simply do:

temps_c <- c(20, 30, 25)
temps_f <- temps_c * 9/5 + 32

This computes on each element of the vector automatically. We did not have to write

for (i in 1:length(temps_c)) { 
  temps_f[i] = temps_c[i]*9/5 + 32 
} 

…. though we could do that and get the same result, it would be more verbose and usually slower.

However, understanding loops is still important. Some tasks can’t be easily vectorized or it’s more intuitive to write as a loop first. Writing loops in R A for loop in R looks like: for (i in 1:5) { # code to run each time, using i } This would run the loop 5 times, with i taking values 1, 2, 3, 4, 5 in succession. We can loop over elements of a vector too:

values <- c(3, 7, 9)
for (v in values) {
   print(v * 2)
}

This would print 6, 14, 18. (Here v takes each value from values). We also have while loops which continue until a condition is false:

count <- 1
while (count <= 5) {
   print(count)
   count <- count + 1
}

This will print 1 through 5. You have to be careful with while loops to ensure the condition eventually becomes false, otherwise you get an infinite loop.

Conditional execution The if statement in R:

if (condition) {
   # do something if condition is TRUE
} else {
   # do something if condition is FALSE
}

You can also chain multiple conditions with else if:

if (score >= 90) {
   grade <- "A"
} else if (score >= 80) {
   grade <- "B"
} else {
   grade <- "C"
}

R uses == for equality check (e.g., if (x == 0) {…}) and != for not equal. Also remember = is for assignment (though <- is the preferred assignment operator in R), so use == for comparison. ! is used to negate a logical condition (e.g., if (!is.na(x)) {…}), meaning “if x is not NA”. Before runing the bellow, try to think what will happen

!c(TRUE, FALSE, NA)
Group exercise: Pseudocode to R code (10 min)
Consider this task: You have a numeric vector scores of test scores. You want to count how many scores are above 80. 1. Write pseudocode for this task (just in plain steps or comments). 2. Translate your pseudocode into an R loop that accomplishes it. Try it on a sample vector scores <- c(72, 88, 95, 60, 81).
Solution

Pseudocode (one possible approach):

set counter = 0

for each score in scores: if score > 80: counter = counter + 1 return counter

R code:

scores <- c(72, 88, 95, 60, 81)

counter <- 0

for (s in scores) { if (s > 80) { counter <- counter + 1 } }

counter

counter should be 3 for the example vector (since 88, 95, 81 are > 80)

Alternatively, a vectorized solution without an explicit loop would be:

sum(scores > 80)

since scores > 80 produces a logical vector and sum() of TRUE/FALSE treats TRUE as 1 and FALSE as 0.

In the solution above, we also showed a more idiomatic R way: using sum(scores > 80) to count, or even table(scores>80). This highlights how R’s vector operations can simplify tasks. But it’s still important to learn loops and if logic, because not everything can be neatly vectorized, and clarity sometimes trumps cleverness.

Understanding functions in R

In Day 2, we freely used functions like mean() or read.csv(). Functions are like mini-programs: they take inputs (arguments) and return an output. In R, you can write your own functions to avoid repeating yourself.

For example, suppose throughout our analysis we need to convert lengths from centimeters to inches (maybe some collaborator uses inches). Instead of repeatedly writing value/2.54 (since 1 inch = 2.54 cm), we can write a function:

cm_to_in <- function(cm) {
  inches <- cm / 2.54
  return(inches)
}

Now we have defined cm_to_in() that we can call anywhere: cm_to_in(10) # returns 3.937008 inches

If we pass a vector, it will return a vector (because the division operation is vectorized).

Functions can have multiple arguments, default values, etc. The general form is: my_function <- function(arg1, arg2 = default_value, …) { # code that uses arg1, arg2, … # optionally a return() call (if omitted, the last expression’s value is returned) }

Why write functions? - Avoid repetition: If you find yourself copying and pasting a block of code with minor changes, that’s a candidate for a function. Write it once, parametrize the parts that change (as arguments), then call it whenever needed. - Clarity: Good function names make code easier to read (“calculate_index(df)” is more descriptive than a dozen lines of code doing it in place). - Fix it once: If you need to change the logic, you only update the function, not every occurrence in your code. - Testing: You can test a function on known inputs (unit testing) to be confident it works, then use it throughout your analysis.

Group exercise: Write a simple function (5 min)
Write an R function fahrenheit_to_celsius(temp_f) that converts a temperature from Fahrenheit to Celsius. The formula is \(C = (F - 32) \times 5/9\). Test your function on the values 32°F (should get 0°C) and 98.6°F (should get ~37°C).
Solution Function definition: fahrenheit_to_celsius <- function(temp_f) { temp_c <- (temp_f - 32) * 5/9 return(temp_c) } Testing it: fahrenheit_to_celsius(32) # returns 0 fahrenheit_to_celsius(98.6) # returns 37 (actually 37 exactly in this case) Notice that if you pass a vector, e.g. fahrenheit_to_celsius(c(32, 212)), it will return 0 100 (since 212°F is 100°C). The function operates on each element, leveraging R’s vectorized arithmetic.

A brief note on packages

R’s power comes not only from the base language, but from its vast ecosystem of packages. A package is a collection of functions, data, and documentation that extends R’s capabilities. For example: - dplyr: for data manipulation (we’ll use it later for cleaning). - ggplot2: for advanced plotting. - readr: faster CSV reading functions. - sf: for spatial data operations. - … and thousands more for every niche (genomics, image analysis, etc.). To use a package, you first install it (one-time) with install.packages(“packageName”), then load it in each session with library(packageName). Once loaded, you can use the functions it provides. For instance: install.packages(“ggplot2”) # run once library(ggplot2) # load the package ggplot(data = trees, aes(x = species, y = dbh_cm)) + geom_boxplot() This would create a nicer boxplot of dbh_cm by species using the ggplot2 grammar of graphics. We won’t dive deep into packages today, but it’s good to know they exist. In fact, R itself is a collection of packages (base R plus recommended). When you load RStudio, some packages like stats and utils load by default. R philosophy: There’s a saying, “There’s probably a package for that.” If you find yourself needing functionality beyond basic R, chances are someone in the community has created a package. Reusing these is often better than reinventing the wheel. It’s a key skill to learn how to find and use packages (CRAN, Bioconductor, GitHub are common sources) as you progress.

Classic values in programming (and why they exist)
  • 🔢 Correctness over cleverness
    Code must first be right. Elegant nonsense is still nonsense.
    Most catastrophic bugs are not complex, they are wrong.

  • 🧮 Explicit types matter
    Knowing whether something is an integer or a floating-point number is not pedantry.
    It is the difference between counting trees or measuring height.

  • ⚠️ Limits are real
    Every data type has bounds. Ignore them and reality will remind you. Loudly.
    Famous example: a rocket self-destructed because a 64-bit float was forced into a 16-bit integer. Overflow. Boom.

  • 🧠 Clarity beats brevity
    Code is read more often than it is written.
    Your future self is a hostile reviewer with no patience.

  • 🔁 Reproducibility is a feature, not a luxury
    If you cannot rerun it, you did not really do it.
    Science and software share this moral spine.

  • 🧪 Fail fast, fail loud
    Silent errors are the most dangerous kind.
    Warnings and crashes are annoying. Wrong results are lethal.

  • 📏 Precision is not accuracy
    More digits do not mean more truth.
    Double precision gives you range and speed, not philosophical certainty.

  • 🚀 Never assume “this will never happen”
    It already has.
    Usually at scale.
    Usually in production.
    Sometimes at launch.


Wrap-up

Today we bridged the gap between knowing what we want to do and telling the computer how to do it. We discussed algorithms as the logical recipes behind every analysis task, and we practiced writing these instructions in R. We covered a lot of ground: R data types and structures, how to control the flow of a program with loops and conditions, and even how to write your own functions to extend R. You might be thinking, “That’s a lot to remember!” And indeed, becoming comfortable with programming takes practice. The key takeaway is that programming is about breaking problems into clear steps and knowing the tools R provides to implement those steps. With these fundamentals, you can start to tackle tasks that were tedious or impossible to do in Excel, like looping through hundreds of files or applying complex logic consistently. Our Belize case study might involve, for example, writing a loop to go through many survey files and extract a summary from each – something that would be extremely painful to do by hand. With your new skills, such tasks are within reach. In the next session (Day 4), we will apply programming to clean and transform data, pushing further into making our workflow reproducible. We’ll see how writing scripts and using version control can make our scientific work more reliable and shareable. Don’t worry if not everything clicked immediately. You now have a mental model of what’s possible, and each time you practice, these concepts will become more natural. Use the exercises and examples as references. And remember: even experienced programmers frequently look up documentation and examples – that’s part of the process!


Reflection
  • Which part of programming today was most challenging to you (e.g., understanding a loop vs. vectorized approach, or remembering the syntax)?
  • Think of a repetitive task in your own work or research. How could you break it into algorithmic steps, and what benefit would automating it bring?
  • Are there any operations or analyses you wish you could do faster or more reliably? Keep those in mind as motivation to practice and learn more coding. Please provide your feedback on today’s session: Anonymous feedback