library(learnr)
tutorial_options(exercise.reveal_solution = FALSE)
gradethis::gradethis_setup()

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = ">",
  error = TRUE
)
set.seed(123)

Control flow

Comparisons -- testing for equality and difference

These tests are essential for while loops to determine whether to continue through the next iteration of the loop, and other forms of flow control such as if statements, to determine what to do next. They allow us to test whether something is true, and change what lines of code are run depending on the outcome. There are the basic tests:

There are then three basic ways of changing or combining the above:

Remember to use (lots of!) brackets to ensure you are combining things in the right order.

Comparisons are also covered in passing in R4DS, and by R Coder in a bit more depth here.

if and if else statements

The if command allows us to perform a test, and if the result is TRUE run a block of R code (in curly brackets { ... }). Optionally, if the test is FALSE, a different block of code can be run instead. This allows us to do a variety of things. To give a very simple example:

if (2 > 1) {
  print("Maths works!")
}

This prints "Maths works!" because the test is TRUE, so the code block that follows is run. You can try changing the numbers to get a different result. Whereas:

if (2 >= 5) {
  print("At least 5.")
} else {
  print("Less than 5.")
}

This prints "Less than 5." because the test was false, so R continues to the code block after the else statement. Again, change the numbers to check you understand how it works. If there is no else statement, then no code is run, so:

if (2 >= 5) {
  print("At least 5.")
}

does nothing. R Coder covers the basics of if statements here. R4DS seems to consider them too simple, but ironically they have a chapter in Advanced R; however, this contains a lot of advanced topics in flow control that are well beyond the scope of this course.

More complex comparisons

Finally note that, when you are doing comparisons, if you have a vector then then any comparisons happen multiple times:

4 > 5

6 > 5

c(2, 4, 6, 3, 1) > 5

You should be able to see that single numbers give single answers, but a vector gives one answer per element of the vector, so you end with a vector of the same size, but with TRUEs and FALSEs in it. This can be very useful sometimes. Consider for instance how you ask "Which of these numbers are greater than 0?":

numbers <- c(-2, 4, 6, -3, 0)
numbers > 0
numbers[numbers > 0]

Or just "How many of these numbers are greater or equal to than 4?":

numbers <- c(-2, 4, 6, -3, 0)
sum(numbers >= 4)

It turns out that TRUE counts as 1 and FALSE counts as '0' in R, so adding up the booleans just gives you the number of TRUEs.

Exercises

Now try it yourself. Complete the following code chunk, such that x is correctly identified as a negative number.

x <- -1

if (___) {
  print("Positive number")
} else {
  print("Negative number")
}
x <- -1

if (x > 0) {
  print("Positive number")
} else {
  print("Negative number")
}
grade_this_code()

Of course, this statement isn't entirely accurate, since 0 is neither positive nor negative. You can fix this by correcting this code:

x <- 0

if (___) {
  print("Positive number")
} else if (___) {
  print("Negative number")
} else
  print("Zero")
x <- 0

if (x > 0) {
  print("Positive number")
} else if (x < 0) {
  print("Negative number")
} else
  print("Zero")
grade_this_code()

Run the following code. There are two errors, try to find them.

x <- 3
y <- 3

if (x - y) {
  print("x is less than y")
} else if (x + y) {
  print("x is greater than y")
} else 
  print("x equals y")
x <- 3
y <- 3

if (x < y) {
  print("x is less than y")
} else if (x > y) {
  print("x is greater than y")
} else 
  print("x equals y")
grade_this_code()

Now edit the following code chunk so that This statement is true is always returned.

if (___) {
  print("This statement is true")
} else {
  print("This statement is false")
}
**Hint:** The value `TRUE` is always true, so will succeed in a if statement, and the value `FALSE` is always false, so will fail.
if (TRUE) {
  print("This statement is true")
} else {
  print("This statement is false")
}
grade_this_code()

Finally, edit this code so that it returns how many of the elements of the vector numbers are greater than zero:

numbers <- c(0, 0, 0, 1, 0, 10, 3, 0)
sum(numbers ____)
numbers <- c(0, 0, 0, 1, 0, 10, 3, 0)
sum(numbers > 0)
grade_this_code()


IBAHCM/RPiR documentation built on Jan. 12, 2023, 7:41 p.m.