R Beginners Course 2026

Introduction to R and Basic Programming Concepts

Bioinformatics Core Facility CECAD

2026-05-21

Session 3 :: More Basic Concepts in R

Control Flow

Learning Purpose

  • Learn how R makes decisions by evaluating logical conditions.
  • Control which code is executed based on different outcomes.
  • Use conditional statements to create flexible and interactive scripts.
  • Select the appropriate decision-making structure for different tasks.
  • Build a foundation for writing more advanced R programs.



Learning Objectives

  • Use comparison and logical operators to create conditions.
  • Use if statements to execute code when a condition is TRUE.
  • Use if...else and if...else if...else to choose between multiple actions.
  • Use switch() to select one option from several predefined choices.
  • Write clear and well-structured conditional code and debug common control flow errors.

Control Flow

  • if is used to evaluate whether a statement is TRUE or FALSE
  • If the statement is TRUE, the code block is executed
  • If the statement is FALSE, the code block is skipped
x <- 30L
if(is.integer(x)) {
   print("X is an Integer")
}
[1] "X is an Integer"

if A B Condition A->B E C if Conditional Code D C->D D->E B->C:n True B->D False

  • if-else is used to evaluate whether a statement is TRUE or FALSE
  • If the statement is TRUE, the first code block is executed
  • If the statement is FALSE, the second code block is executed
x <- c("what","is","truth")
if("Truth" %in% x) {
   print("Truth is found")
} else {
   print("Truth is not found")
}
[1] "Truth is not found"

else A B Condition A->B E C if Conditional Code F C->F D else Conditional Code D->F F->E B->C True B->D False

  • switch is used to select one of several code blocks to be executed
  • The switch function takes an expression and a list of cases
x <- switch(
   3,
   "first",
   "second",
   "third",
   "fourth"
)
print(x)
[1] "third"

switch A B Expression A->B F C Code block 1 C->F D Code block 2 D->F E Code block 3 E->F B->C Case 1 B->D Case 2 B->E Case 3

R Loops

Learning Purpose

  • Learn how to repeat tasks efficiently without writing the same code multiple times.
  • Understand how loops automate repetitive operations in R.
  • Control the execution of code across sequences and conditions.
  • Use loops to process data step by step.
  • Build a foundation for more advanced programming and data analysis tasks.



Learning Objectives

  • Use for loops to iterate over sequences, vectors, and lists.
  • Use while loops to repeat code as long as a condition remains TRUE.
  • Use repeat loops for indefinite iteration with explicit stopping conditions.
  • Apply next and break to control loop behavior.
  • Write clear, efficient, and well-structured looping code in R.

R Loops

v <- LETTERS[1:4]
#
for ( i in v) {
   print(i)
}
[1] "A"
[1] "B"
[1] "C"
[1] "D"

v <- c("Hello","while loop")
cnt <- 2

while (cnt < 7) {
   print(v)
   cnt = cnt + 1
}
[1] "Hello"      "while loop"
[1] "Hello"      "while loop"
[1] "Hello"      "while loop"
[1] "Hello"      "while loop"
[1] "Hello"      "while loop"

v <- c("Hello","loop")
cnt <- 2

repeat {
   print(v)
   cnt <- cnt + 1
    
   if(cnt > 5) {
      break
   }
}
[1] "Hello" "loop" 
[1] "Hello" "loop" 
[1] "Hello" "loop" 
[1] "Hello" "loop" 

v <- LETTERS[1:6]
for ( i in v) {
   
   if (i == "D") {
      next
   }
   print(i)
}
[1] "A"
[1] "B"
[1] "C"
[1] "E"
[1] "F"

The apply family

Learning Purpose

  • Replace repetitive for-loops with simpler function-based operations
  • Enable faster and more efficient data processing in R
  • Perform operations on lists, vectors, matrices, and grouped data easily
  • Improve code readability and reduce programming errors
  • Support scalable and flexible data manipulation workflows



Learning Objectives

  • Understand how to use apply-family functions instead of loops
  • Identify which apply function fits different data structures (vector, list, matrix)
  • Learn to apply functions across rows, columns, or groups efficiently
  • Improve ability to write cleaner and more compact R code
  • Develop basic functional programming thinking in R

The apply family

An apply function is essentially a loop, but run faster than loops and often require less code. The apply family of functions is a set of functions in R that allow you to apply a function to the rows or columns of a matrix or data frame. The main functions in the apply family are:

mtrx <- matrix(c(1:10, 11:20, 21:30), 
               nrow = 10, ncol = 3)
mtrx
      [,1] [,2] [,3]
 [1,]    1   11   21
 [2,]    2   12   22
 [3,]    3   13   23
 [4,]    4   14   24
 [5,]    5   15   25
 [6,]    6   16   26
 [7,]    7   17   27
 [8,]    8   18   28
 [9,]    9   19   29
[10,]   10   20   30
apply(mtrx, 1, sum) # row-wise
 [1] 33 36 39 42 45 48 51 54 57 60
apply(mtrx, 2, sum) # column-wise
[1]  55 155 255
st.err <- function(x){
  sd(x)/sqrt(length(x))
}
apply(mtrx,2, st.err)
[1] 0.9574271 0.9574271 0.9574271

lapply is used to apply a function to each element of a list or vector and returns a list. It is useful when you want to apply a function to each element of a list and return the results in a list format.

A<-c(1:10)
B<-c(11:20)
C<-c(21:30)
my.lst<-list(A,B,C)
lapply(my.lst, sum)
[[1]]
[1] 55

[[2]]
[1] 155

[[3]]
[1] 255

sapply is a simplified version of lapply. It tries to simplify the result to a vector or matrix if possible.

sapply(my.lst, mean)
[1]  5.5 15.5 25.5

vapply is similar to sapply, but it requires you to specify the type of output you expect. This can help prevent unexpected results.

vapply(my.lst, mean, numeric(1))
[1]  5.5 15.5 25.5

tapply is used to apply a function to subsets of a vector, based on a grouping factor. It is useful for performing calculations on subsets of data.

tapply(iris$Sepal.Length, iris$Species, mean)
    setosa versicolor  virginica 
     5.006      5.936      6.588 

mapply is a multivariate version of sapply. It allows you to apply a function to multiple arguments in parallel.

A
 [1]  1  2  3  4  5  6  7  8  9 10
B
 [1] 11 12 13 14 15 16 17 18 19 20
C
 [1] 21 22 23 24 25 26 27 28 29 30
mapply(sum, A, B, C)
 [1] 33 36 39 42 45 48 51 54 57 60