Conditionals and loops

  1. Read CpG island data as shown before (see the Input/Output exercises). Use stringsAsFactors = FALSE.

Here is an explanation of the columns:


  1. First, check “percentage of island that is CpG” values using summary().

  1. Write a function to decide if a given percentage of GC is high, low or medium:
  • low < 60
  • high > 75
  • medium between 60 and 75

Then try your function by evaluating: 35, 12, 60, 90.


  1. Add other conditions to your function:

    • if the number inserted is negative or greater then 100 print “The number is not a percentage”
    • if anyone inserts a value that is not a number print “This is not a number”

    Notice: you have to be really carefull. Only one output is correct.

    Hint: you can do this exercise in several ways; for example, you can nest conditionals or you can use them in series. You are not obligated to use all three if, if else and else.

    Then try your function by evaluating: 35, 12, 60, 110, -3, “A”.


  1. Use a for loop to get GC percentage classes for GC percentages of CpG island on chrX and put them into a vector. Use the function you wrote above.

  1. Subset cpgi keeping only CpG island on chrY, then order rows by perGc values (increasing). Print GC percentage classes of CpG islands until perGc value is < 65. Hint: use a while() loop with an increasing index. What happens if you do not order values before using while loop?

  1. Multiplication table: write an R code that prints out the 9x9 multiplication table. For this problem, you need to use two for statements, one inside the other.

  1. Create a vector v containing 10 personal names. Then:
  • build a loop that ierates on each element in v and assign a name to each element by taking a random number from a gaussian distribution. Then print the element of the vector with its name
  • print the resulting vector

  1. Create a matrix 9x8 with only NAs. Then, use loops and/or conditionals to fill the matrix. In particular:
  • in the fist two rows and three columns you have to put numbers from a uniform distribution
  • in all the columns of the third row you have to put a number of your choice
  • in the rows 4:9 and columns 4:8 you have to put numbers from a gaussian distribution
  • in the first row and 4:8 columns you have to put 0
  • in the rows 4:9 and columns 1:3 you have to put the result of the log10 of the element [4,4] of the matrix

Are there any missing values? At the end test the matrix using is.na()


  1. Write a while loop that at each iteration add a number in the vector x from a gaussian distibution (with mean 0 and sd 1.5) but terminates if you get a number bigger than 3.