18.1 Exercise 11: If statement

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

Answer
getwd()
setwd("~/Rcourse/ExtraModule")

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!”)
Answer
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).
Answer
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")
Answer
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")
}