Lecture 10 - Programming Basics

In this lecture note, we will delve into the core of R programming by exploring its building blocks. Think of R as a language: to communicate effectively, you need to know the grammar (syntax), vocabulary (functions), and the rules of conversation (flow control and loops). Let us unpack these one by one.

R Syntax

my_function <- function(parameters) {
  # Code to execute
  return(result)
}
  • Example:

    add_numbers <- function(a, b) {
      sum <- a + b
      return(sum)
    }
if (condition1) {
  # Code to execute if condition1 is TRUE
} else if (condition2) {
  # Code to execute if condition2 is TRUE
} else {
  # Code to execute if condition1 and condition2 are FALSE
}
  • Example:

    number <- 10
    if (number > 5) {
      print("Number is greater than 5")
    } else {
      print("Number is 5 or less")
    }
for (i in 1:n) {
  # Code to execute for each iteration
}
  • Example:

    for (i in 1:5) {
      print(i)
    }
while (condition) {
  # Code to execute as long as the condition is TRUE
}
  • Example:

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

Core Apply Functions

Function Input Output Description
apply(x, margin, FUN) Mutlidimension (dim) Customizable Applies a function over rows or columns of a matrix or dimensions of an array.
lapply(x, FUN) List-type (as.list) List Applies a function to each element of a list or vector and returns a list.
sapply(x, FUN) List-type (as.list) Simplified Like lapply, but tries to simplify output.
vapply(x, FUN, FUN.VALUE) List-type (as.list) User-defined Like sapply, but enforces a specific return type.