15.1 Exercise 10: For loop

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- Write a for loop that iterates over the sequence of numbers 2 to 10 (both included), and prints the square root of each number (function sqrt()).

correction

2- Write a for loop that iterates over the sequence of numbers 5 to 15 (both included), and prints a new vector of 2 elements containing the number and its square root

correction

3- Create the following matrix

  • Write a for loop that iterates over each row of mat1 and prints the median value of each row.

correction

2- If statement in for loop

Create the following matrix:

Write a for loop that iterates over each row of mat4: if an NA is found, print the row number and the entire row where the NA is found.

correction

3- For loop, if statement and regular expression

Create vector vec4 as:

vec4 contains Human and Mouse gene symbols.

Loop over each element of vec4:

  • If the element is a human gene (both characters and numbers; all characters are written in upper-case), print a vector of two elements: the name of the gene and “human gene”.
  • If the element is a mouse gene (both characters and numbers; only the first character is written 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

How do you get started?

  • First, work on the regular expressions: how do you retrieve Human genes only? How do you retrieve Mouse genes only?
  • Then, integrate the regular expressions in the if statement.
  • Finally, integrate all this in a for loop!


correction