Flow control

  1. if-else
  2. for
  3. while
  4. function

if-else

An if statement consists of a logic condition (TRUE or FALSE) followed by one or more statements.

# Template in words
if(a logic condition) {
  Get inside the curly brackets and 
  run this block when the condition is true
} 
# Example
x = 1
if(x == 1) {
  print("x equals 1")
}
## [1] "x equals 1"

An if statement can be followed by an optional else statement, which executes when the previous logic expression is false.

name="Tim Cook" ; role = "CEO" 
if(role == "CEO") {
  print(paste(name, "is a CEO.", sep=" "))
} else {
  print(paste(name, "is not a CEO.", sep=" "))
}
## [1] "Tim Cook is a CEO."
name = "Jeff Williams" ; role = "COO" 
if(role == "CEO") {
  print(paste(name, "is a CEO.", sep=" "))
} else {
  print(paste(name, "is not a CEO.", sep=" "))
}
## [1] "Jeff Williams is not a CEO."

The logic expression in the previous example is role == "CEO".

Alternatively, you can just use a logic variable (TRUE or FALSE):

name="Tim Cook"
is_ceo = TRUE
if(is_ceo) {
  print(paste(name, "is a CEO.", sep=" "))
} else {
  print(paste(name, "is not a CEO.", sep=" "))
}
## [1] "Tim Cook is a CEO."

You can have more than two decision points:

age = 15
if(age < 13) {
  print("Kid")
} else if (age < 20) {
  # Go into this block if the pervious logic expression is FALSE
  # and the current logic expression is TRUE
  print("Teenager")
} else { 
  # Go into this block if all pervious logic expressions are FALSE
  print("Adult")
}
## [1] "Teenager"

Your turn

Create a variable grade = "A" and use if-else statements to print its respective value in a 4.0 scale based on the following conversion table. Try different letter grades to see if your if-else statements are correct.

Letter Point
A 4
B 3
C 2
D 1
All other letters 0

for loops

You often encounter situations when you need to perform the same statements multiple times, potentially over a set of data objects.

Motivating example:

print( paste("The year was", 2001) )
print( paste("The year was", 2002) )
print( paste("The year was", 2003) )
print( paste("The year was", 2004) )

A for loop iterates through every element in a vector.

# Template in words
for (element in vector){
  Use the element to do something
}
# Example
for (year in 2001:2004){
  print( paste("The year was", year) )
}
## [1] "The year was 2001"
## [1] "The year was 2002"
## [1] "The year was 2003"
## [1] "The year was 2004"

In words, for each year that is in the sequence 2001:2004, you execute the code chunk print( paste("The year was", year) )

# you could define the vector outside the for-loop
x = c(1, 3, 5)  
for(i in x) {
  print(i)
}
## [1] 1
## [1] 3
## [1] 5
# it works regardless the data type of the vector
for(i in c("A", "B", "C", "D")) { 
  print(i)
}
## [1] "A"
## [1] "B"
## [1] "C"
## [1] "D"

If you want to skip some items in a for-loop, use the keyword next.

for (i in 1:5) {
  if (i == 2){
    next
  }
  print(i)
}
## [1] 1
## [1] 3
## [1] 4
## [1] 5

Your turn

Continue with our previous exercise on converting letter grades to grade points.

Put letter grades (A, A, C, B, B) in a vector and use for-loop to print out their respective points.

while loops

The while loop continually executes a block of statements while a particular condition is true.

# Template in words
while(condition to check) {
  statements to run when the condition is true
}
# Example
x = 1
while(x <= 3) {
  print(x)
  x = x + 1 # what would heppen if you skip this line?
}
## [1] 1
## [1] 2
## [1] 3

for() vs. while()

for() is better when you want to iterate over a set of elements that you know in advance

while() is better if you find it easy to specify when to run and when to stop.

Note: Every for() could be replaced with a while()

Your turn

  1. Use a for loop to get the sum of all numbers from 1 to 100

  2. Use a while loop to get the sum of all numbers from 1 to 100

    • Hint 1: Create a variable total outside the for/while loop, and change the value of total as you looping through all numbers from 1 to 100
    • Hint 2: You can verify your answer against R’s internal sum() function: sum(1:100)

Functions

A function is a procedure or routine which takes optional inputs and produces an optional output.

So far we have already seen many built-in functions:

  • Vector
    • seq(), rep(), mean(), length(), …
  • Data frame
    • colnames(), rownames()
  • Character string
    • paste()

Why functions?

  • Data structures tie related values into one object

  • Functions tie related commands into one object

  • In both cases: easier to understand, easier to work with, easier to build into larger things

What should be a function?

  • Things you’re going to re-run, especially if it will be re-run with changes
  • Chunks of code you keep highlighting and hitting return on
  • Chunks of code which are small parts of bigger analyses
  • Chunks which are very similar to other chunks

Creating functions

In R, you can create your own functions using the following syntax:

my_function <- function(input1, input2, ...) {
  # Use the input to do something 
  return(output) # return a result
}

Here is a working example:

hello_world <- function() { # this particular function requires no inputs
  print("Hello world!")
  # This function has no return statement; return nothing.
}

hello_world()  # call the function; don't forget the parentheses
## [1] "Hello world!"

Another example:

add_one <- function(num) {
  num = num+1  # be sure to match the input variable name 
  return(num)  # return() says what the output is
}
a = add_one(10)
print(a)
## [1] 11

More than one input

greeting <- function(your_name, course_name) {
  print(paste0("Hello, ", your_name, ". This is ", course_name))
}

greeting(your_name="Smith", course_name="CIS 4730") 
## [1] "Hello, Smith. This is CIS 4730"
greeting("Alice", "CIS 4950") 
## [1] "Hello, Alice. This is CIS 4950"

Your turn

  1. Write a function that takes two numerical values and return the multiplication of these two values.

  2. Create a vector stop_words to store the following stop words: a, an, and, the, that. Then write a function detect_stop_word that take a word as input and detect if the word is a stop word.

    • Hint: recall the %in% operator from lab-02
detect_stop_word("atlanta")
## [1] FALSE
detect_stop_word("that")
## [1] TRUE