Worksheet

This page contains a number of exercises to give you a chance to practise what you have learned this session. You should create a new .R R file for each of them.

Exercise 1

Create a list containing 5 different animal types, for example:

  • cat
  • dog
  • elephant
  • minnow
  • beaver

Print out the list to the screen.

exercise1.r
animal_list <- c("cat", "dog", "elephant", "minnow", "beaver")

cat(animal_list)
cat dog elephant minnow beaver
Exercise 2

Start by copying the code that you used to create the list of animals in the last exercise. Write a loop which will print out each of the animals, prefixed with Species:. For example the output could look like:

Species: cat
Species: dog
Species: elephant
Species: minnow
Species: beaver
exercise2.r
animal_list <- c("cat", "dog", "elephant", "minnow", "beaver")

for (animal in animal_list) {
    cat("Species:", animal, "\n")
}
Species: cat 
Species: dog 
Species: elephant 
Species: minnow 
Species: beaver 
Exercise 3

Create a list containing 10 different numbers, ranging from 0 to 100. For example: 65, 54, 17, 78, 66, 24, 32, 80, 79, 95.

Write a loop which will print out only those numbers which are larger than 50.

exercise3.r
my_numbers <- c(65, 54, 17, 78, 66, 24, 32, 80, 79, 95)

for (num in my_numbers) {
    if (num > 50) {
        cat(num,"")
    }
}
65 54 78 66 80 79 95 
Exercise 4

Create a loop which iterates over the numbers from 1 to 20 (inclusive). Inside the loop: - if the number is divisible by three then print “ook”, - if the number is divisible by both three and five then print “foo”, - and if the number is not divisible by either then just print the number.

Hint: You can use the % operator to find the remainder from a division. Also, take care in the order that you do your if-else.

When creating a chain of if-else if-else, you should put the most specific checks first. Otherwise they will be swamped by the more general checks.

exercise4.r
for (i in 1:21) {
    if ((i%%3)==0 & (i%%5)==0) {
        cat("foo", "")
    } else if ((i%%3)==0) {
        cat("ook", "")
    } else {
        cat(i, "")
    }
}
1 2 ook 4 5 ook 7 8 ook 10 11 ook 13 14 foo 16 17 ook 19 20 ook