15.1 Exercise 10: If statement

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

correction

1- Create vector vec2 as:

  • 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

## [1] "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 for a second condition (using else if) that checks if “pear” is found.

correction

## [1] "there is no grapefruit 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:

correction

## [1] "there is no grapefruit but there is a pear"

2- If statement in for loop

Create the following matrix:

Loop over rows with for of mat4 and print row number and entire row if you find an NA.

correction

## [1] 3
## [1]  1 NA
## [1] 4
## [1] NA  0

3- For loop, if statement and regular expression

Create vector vec4 as:

Loop over each element of “vec4”: * If the element is a human gene (all upper-case characters), print a vector of two elements: the name of the gene and “human gene”.
* If the element is a mouse gene (only the first character is in upper-case), print a vector of two elements: the name of the gene and “mouse gene”.

Tip 1: Use grep and a regular expression in the if statement !
Tip 2: When grep does not find a match, it returns an element of length 0 !
Tip 3: You can also use grepl: check the help page

correction

## [1] "Oct4"       "mouse gene"
## [1] "DEPP"       "human gene"
## [1] "RSU1"       "human gene"
## [1] "Hk2"        "mouse gene"
## [1] "ZNF37A"     "human gene"
## [1] "C1QL1"      "human gene"
## [1] "Shh"        "mouse gene"
## [1] "Cdkn2a"     "mouse gene"
## [1] "Oct4"       "mouse gene"
## [1] "DEPP"       "human gene"
## [1] "RSU1"       "human gene"
## [1] "Hk2"        "mouse gene"
## [1] "ZNF37A"     "human gene"
## [1] "C1QL1"      "human gene"
## [1] "Shh"        "mouse gene"
## [1] "Cdkn2a"     "mouse gene"