Control Flow

Choices and Iteration

Choices

Getting to Campus

If my bike is working
     then I ride my bike to campus.

If my bike is not working and I have enough time
     then I ride the bus to campus.

If my bike is not working and I don’t have enough time
     then I take a cab.

A random condition in R

rnorm(1)
[1] -1.671851

rnorm() will generate a random number from a Normal distribution with mean 0 and SD 1.

if-then

“if then” statement: executes a block of code if a condition is met.

x <- rnorm(1)

if (x > 0) {
  print("x is positive :)")
}

if-else

“if else” statement: executes one block of code if a condition is met and a different block of code if it is not met.

x <- rnorm(1)

if (x > 0) {
  print("x is positive :)")
} else {
  print("x is negative :(")
}

Nested ifs

x <- rnorm(1)

if (x > 0) {
  print("x is positive :)")
} else if (x < 0) {
  print("x is negative :(")
} else {
  print("x is zero :|")
}

Getting to Campus

If my bike is working
     then I ride my bike to campus.

If my bike is not working and I have enough time
     then I ride the bus to campus.

If my bike is not working and I don’t have enough time
     then I take a cab.

Question

Using the R objects bike_working and enough_time, both logical vectors of length 1, write this decision tree in R using nested if-then statements and print().

02:30

if (bike_working) {
  print("ride bike")
} else if (enough_time) {
  print("ride bus")
} else {
  print("call cab")
}

Iteration

For loops

Prof. Sanchez Slides

for (item in vector) {
    perform_action
}

Iterated Choices

What if x has multiple elements?

x <- rnorm(3)
x
[1]  0.09551927  0.86368641 -2.28866538




      if (x > 0) {
        print("x is positive :)")
      }

Option 1

for (i in 1:length(x)) {
  if (x[i] > 0) {
    print("x is positive :)")
  }
}
[1] "x is positive :)"
[1] "x is positive :)"

Option 2

for (i in 1:length(x)) {
  if (x[i] > 0) {
    print(paste("element", i, "is positive :)"))
  }
}
[1] "element 1 is positive :)"
[1] "element 2 is positive :)"

Option 3

for (x_elem in x) {
  if (x_elem > 0) {
    print(paste(x_elem, "is positive :)"))
  }
}
[1] "0.0955192748637143 is positive :)"
[1] "0.863686410991415 is positive :)"

ifelse()

ifelse(): A vectorized if-else statement.


x < 0 
[1] FALSE FALSE  TRUE
ifelse(test = x < 0, yes = "is positive :)", no = "is negative :(")
[1] "is negative :(" "is negative :(" "is positive :)"