© Copyright 2016 Dr Marta Milo, University of Sheffield.
Week 1 Practical - Solutions
This Notebook contains the solution of the practical assignments for Week 1.
The solution to the exercises assigned but they are not unique. All the exercises proposed can be solved in different manners, some more eficient than other but still correct is the requested output is obtained.
For this reason, when you compare your solutions with these bear in mind that you might have found the solution using a different algorithm and different commands, nonethless they are still correct. These solutions are a guidance and also a surce of ideas that can be merged with yours to build your scripts and to improve it.
To help you to evaluate your notebooks please follow the following criteria:
Overall clarity (score = 0.25)
Correctness of the code (score = 0.25)
Exhaustive cover of required analysis (score= 0.25)
Interpretation of the results (score= 0.25)
These criteria are also used when peer-marking and self-marking. Please read the guidelines given to quantify the above criteria with a grade. For Week 1 please score the notebook starting from Excercise 1.
Basic operation in R
Exercise 0: Create a notebook called your_username_week1.ipynb in the Week 1 folder. This is OBviuosly done successfully if you are reading your notebook. 😃
Exercise 1: In your notebook called your_username_week1.ipynb, open a code cell execute the command library()
results in. What happens if you type library without parentheses? Write a description of what you've discovered in a Markdown cell
Solution:
Typing the command library()
you do not get any output. The function library()
attivates the package ( a collection of functions) that you specify in brackets. If you do not specify anything it will return a void value and no effect on the working environment.
Typing the command library
echos the code that implements the function library().
Changing path and verifying location of workspace
Exercise 2: Run the setwd command above in your your_username_week1.ipynb notebook. Verify that you are indeed in the Autumn2016 directory and then set your working directory to be Autumn2016/Week1
I have verified that I am in the directory I wanted to get with the command getwd()
before doing any other operation.
Variables
In the above code cell x
is variable, x is its name and 1 its value. The symbol <-
assigns a value to an object. Basic arithmetic operations can also be done with vectors. The 'raise to the power' operation is performed with the symbol ^
. For example three raised to the power 2 is given by 3^2
** Exercise 3:** In your notebook called your_username_week1.ipynb:
Assign the values "3", "10" and "15" to three different objects and perform the following operations storing the results into different objects:
sum all three variables
take the difference of the first two and divide by the third
multiply all three together
take the square value of the sum
calculate the sum of the vector raised to the power of 4
take the square root (sqrt) of the difference of thrird and the first
Exercise 4: In your notebook called your_username_week1.ipynb:
Write code to print your name, your email and the module code separated by a comma.
Vectors and Matrices
Exercise 5:
In your notebook called your_username_week1.ipynb:
Create a sequence of even numbers ranging from 2 to 30. Create a sequence of odd numbers ranging from 1 to 30. Verify the lengths and calculate the sum of the elements of the even sequence and the sum of the elements of the odd sequence. What are the two values? Calculate the sum of a sequence of numbers ranging from 1 to 30. What do you conclude?
To verify the length I use the function length()
The two sequences has the same number of elements since the numbers are consecutive and the range ends with an even number.
The sum of the sequence is given by the sum of the odds and the evens, this is because they are consecutive numbers.
** Numbers as characters**
We can transform numbers to characters using the command as.character()
. For example
This enable us to concatenate vectors with letters and numbers that are coerced into characters.
Exercise 6: In your notebook called your_username_week1.ipynb:
Create a vector with the following strings: "BMS", "APS", "MBB". Create a vector with the following numbers: 353, 227, 253.
concatenate the two vectors
create a vector of three elements merging the elements of the two vectors. For example the first element will be BMS353
It is possible to use a loop structure like for
to repeat a set of instruction for a number of times (in this case 3 times). The counter i
tells when to exit loop.
We more often use the command matrix(), to create a matrix or rearrange a set of data. matrix() needs the data, nrow, ncol. For example matrix(data, nrow = 4, ncol = 5)
We can index the elements of M in the same way we used for vectors. The only difference: now we need two indices in the square brackets, because M is two-dimensional. The first index corresponds to the rows, the second to the columns.
Exercise 7: Create new matrices with:
The 2x2 matrix forming the upper left corner of M
The first two rows with the third column missing
Second row with all columns
Comment on dimensions of all these new matrices.
The matrix M has the following form:
The matrices created hgave the following dimensions: M1=[2x2]; M2=[2x3] and M3=[1x5]
We can now access the data in the matrix using names as index.
Exercise 8: In your notebook called your_username_week1.ipynb:
Create a [3x3] matrix containing the number of students for the year "2013-14", "2014-15", "2015-16" in the three module which names are the ones you created in Exercise 6. Use invented numbers. Assign names to columns and rows and print the number of student for BMS353 for all years.
It also possible to use directly the name of the column instead of the index when creating new column, i.e AA["APS227",]<-c(160,170,300)
Exercise 9: In your notebook called your_username_week1.ipynb:
Create two matrices [3x4] of 12 random integers from 1:100.
sum the matrices
subtract the matrices
multiply the matrices (to perform matrix multiplication you need to use
%*%
operator. You also want to make sure the dimensions are compatible)calculate the square root of the elements of the matrices
Create the matrices using sequences of random generated number and table them into matrices.
Sum of the matrices:
Subtraction of matrices
Multiplication of the matrices.
In order to multiply S1 and S2 I need to make sure the dimensions are compatible, therefore I need to transpose ( change the row with the column) of one of the two. S1=[3x4] and S2=[3x4], the number of col of S1 needs to be the same as the number of row of S2.
Square root of the elements of the matrices
Create user-defined functions in R
In R it is possible to create small routines ( or functions) that can be called using a single word. For example we can create a function called myFunction which takes a value, raises it to the power of 3 and subtract 1. It will be something like
What would be the value of test
?
IT WOULD BE 7
Exercise 10: In your notebook called your_username_week1.ipynb:
Calculate the sample variance of using the formula below. The formula of the sample variance is:
.
what happens if you use the command var(x)
?
Tip: Remember to use the command sum()
.
The function var()
implements the sample variance for a set of numbers.
Exercise 11 In your notebook called your_username_week1.ipynb:
Create a user-defined function that accepts more than one input argument. This function can do anything you like. Be creative!
I will implemet the normal function in R using a user-defined function. The normal function has the folowing formula:
Exercise 12 In your notebook called your_username_week1.ipynb:
Write a brief summary in bullet points of the content of this week practical
Changing path and verifying location
Manipulate variables
Manipulate vector and matrices
Use of strings and numbers in vectors
Create your user-defined function