Control Structures & Functions

CSULB Intro to R

April 13, 2018

Agenda

  1. Control Structures
  2. Functions
  3. Packages
  4. Helpful resources

Control Structures

for loops

print(paste("The year is", 2016))
## [1] "The year is 2016"
print(paste("The year is", 2017))
## [1] "The year is 2017"
print(paste("The year is", 2018))
## [1] "The year is 2018"

for loops

for(i in 2016:2018){
  print(paste("The year is", i))
}
## [1] "The year is 2016"
## [1] "The year is 2017"
## [1] "The year is 2018"

for loops

vec <- seq(2, 20, by = 2)
newvec <- vector("numeric", length = length(vec)) # equivalent: numeric(length(vec))
for(i in 1:length(vec)){
  newvec[i] <- vec[i]^2
}
newvec
##  [1]   4  16  36  64 100 144 196 256 324 400
# advanced: vec^2

if/else statements

x <- 7
if (x < 10){
  print("x is less than 10")
}else{
  print("x is greater than 10")
}
## [1] "x is less than 10"

Combining for loops and if/else statements:

age <- sample(1:100, 10)
ageCat <- rep(NA, length(age))
for (i in 1:length(age)) {
    if (age[i] <= 35){
       ageCat[i] <- "Young"
      }else if (age[i] <= 55){
        ageCat[i] <- "Middle-Aged"
      }else{
         ageCat[i] <- "Old"
      } 
}
age.df <- data.frame(age = age, ageCat = ageCat)
age.df[1:3,]
##   age      ageCat
## 1  82         Old
## 2  44 Middle-Aged
## 3  95         Old

Other Controls

Functions

How to write functions

Active Learning

Active Learning

Initialize \(tallest\) = \(height_1\)
For each \(element\) in \(H\), do
    If \(element > tallest\), then
    \(tallest = element\)
end for
return \(tallest\)

myHeights <- c(63, 58, 72, 65)

findTallest <- function(H){
  # initialize tallest
  tallest <- H[1]
  
  # search through all heights in H
  for(height in H){
    if(height > tallest){tallest <- height}
  }
  
  # spit out the tallest height after for-loop has run
  return(tallest)
}

Up Next