exercise1.r
<- c("cat", "dog", "elephant", "minnow", "beaver")
animal_list
cat(animal_list)
cat dog elephant minnow beaver
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.
Create a list containing 5 different animal types, for example:
Print out the list to the screen.
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
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.
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.