Chapter 7 Conditionals
So far, each statement in our code was executed one by one. Conditionals are structures which allow you to have alternative code executed depending on some condition. This creates more complex behavior and more interesting functionality.
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.
The expression can be arbitrarily complicated, but must evaluate to a single logical value.
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"7.0.1 Exercises: Conditionals
See Section 18.0.18 for solutions.
Write a conditional that sets
x <- x + 1ifxis even.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).Consider two vectors
xandyand write a conditional that prints the name of the longer vector or “equal” in case they are of the same length. Test withx <- 1:5andy <- 3:-1.