Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

MATH377: Financial and Actuarial Modelling in R

Tutorial 2

Exercise 1. Create three vectors of length 3, with content and names of your choice. Next, combine the three vectors into a 3 × 3 matrix where each column represents one of your vectors. Finally, compute the

determinant (det() - is your matrix invertible?) and the transpose of your matrix.

Exercise 2. Consider the following matrix:

matrix(c (c (-4 ,  2 ,  1),  c (0 ,  -1 ,  0.5),  c (1.5 ,  0.2 ,  -2)), ncol  =  3 , byrow  = TRUE)


## ## ## ##

 

[1,] [2,] [3,]


[,1]  [,2]  [,3]

-4.0   2.0    1.0

0.0  -1.0   0.5

1.5   0.2  -2.0


Compute the sum of rows (that is, you have to return a vector of length three with first entry -1) via the following three methods:

a) Using the rowSums() function (see help for more information).

c) Using matrix multiplication.  Hint:  This can be done by multiplying the above matrix with an appropriate vector.

Exercise 3. Write an R program to create a 3-dimensional array of three 4 × 3 matrices with entries of your choice.

Exercise 4. Write an R program to:

a)  Create a numeric vector called rates with values:  0.043, 0.045, 0.041, 0.049, 0.05, 0.055, 0.048, 0.0495, 0.051, 0.044, 0.045, 0.0455.

b)  Create a character vector called months with values: “Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”.

 

and grades

Let us imagine that we want to compute the average grade by age. We can use the tapply() function to do so. Look at the documentation of tapply() (?tapply) and solve the above problem.

Exercise 6. Consider a random variable X with probability density function (pdf)

fX (x) = xe −  ,  x ≥ 0

a) Write an R function to compute the above pdf.

 

i. A sum approximation of the form P f(xi)∆(x), where ∆(x) is a “small” increment. Hint: create a sequence vector (over a relatively large interval and with a small increment), evaluate your function in a) on the sequence vector, multiply the evaluation by the increment and finally sum.


ii. Using the integrate(f,  lower, upper) function. Note: $value gives the value of the integral.

c) Compute the expected value and the variance of X .

 

Exercise 7. We know that

1 +    +    +    + · · · = X 2n  = 2 .

n=0

Using a while loop, find a value N such that

N

2 − X 2n  ≤ ϵ ,

n=0

where ϵ = 0.00001.

Exercise 8.  Write a function that performs the inner product of two vectors using for loops.  Using microbenchmark() compare the performance of your implementation with the inner product using the %*% operator. Try with large vectors, let’s say length 100, and times  =  10000.