## 14.1 Exercise 9: If statement

Create the script “exercise9.R” and save it to the “Rcourse/Module2” directory: you will save all the commands of exercise 9 in that script.
Remember you can comment the code using #.

correction

``````getwd()
setwd("~/Rcourse/Module2")``````

1- Create vector vec2 as:

``vec2 <- c("kiwi", "apple", "pear", "grape")``
• Use an if statement and the %in% function to check whether “apple” is present in vec2 (in such case print “there is an apple!”)

correction

``````if("apple" %in% vec2){
print("there is an apple there")
}``````
• Use an if statement and the %in% function to check whether “grapefruit” is present in vec2: if “grapefruit” is not found, test whether “pear” is found (using else if).

correction

``````if("grapefruit" %in% vec2){
print("there is a grapefruit here")
}else if("pear" %in% vec2){
print("there is no grapefruit here, but there is a pear!")
}``````
• Add an else section in case neither grapefruit nor pear is found in vec2.
Test your if statement also on vec3:
``vec3 <- c("cherry", "strawberry", "blueberry", "peach")``

correction

``````if("grapefruit" %in% vec2){
print("there is a grapefruit here")
}else if("pear" %in% vec2){
print("there is no grapefruit here, but there is a pear!")
}else{
print("no grapefruit and no pear can be found")
}``````