8.1 Conditionals

The R language offers the conditional construction if(expr){ ... } where expr is a logical expression. If the expression is TRUE, the code inside the curly brackets denoted here by ... gets executed, else it is not.

> if(TRUE){ print("yes") }
[1] "yes"
> if(FALSE){ print("yes") }

The expression can be arbitrarily complicated, but must evaluate to a single logical value.

> if(1+2 < 5*20){ print("yes") }
[1] "yes"

The conditional construction can be extended to if(expr){ ... }else{ ... }, which allows for alternative code to be run if the condition is not true.

> x <- 5
> if(3>x){print("yes")} else {print("no")}
[1] "no"
> 
> if(sum(1:x)>10 && x*x < x^x){
+   x <- sqrt(x)
+   print(paste("x is now", x))
+ } else {
+   print(paste("x remains", x))
+ }
[1] "x is now 2.23606797749979"

Obviously, conditionals can be nested.

> x <- 52
> if(x < 0){
+   print("x is negative")
+ } else {
+   if(x %% 2 == 0){
+     print("x is positive and even")
+   } else {
+     print("x is positive and odd")
+   }
+ }
[1] "x is positive and even"

Sometimes, including in the case above, a nested construct can be written more elegantly using the if(){ ... } else if(){ ... } construct.

> x <- 52
> if(x < 0){
+   print("x is negative")
+ } else if(x %% 2 == 0){
+   print("x is positive and even")
+ } else {
+   print("x is positive and odd")
+ }
[1] "x is positive and even"

8.1.1 Exercises: Conditionals

See Section 18.0.18 for solutions.

  1. Write a conditional that sets x <- x + 1 if x is even.

  2. Use conditionals to informs you if the elements of a vector x of length 3 are strictly increasing, or not, by printing an appropriate message. Test it on the vector x <- c(1,4,3).

  3. Consider two vectors xand y and write a conditional that prints the name of the longer vector or “equal” in case they are of the same length. Test with x <- 1:5 and y <- 3:-1.