0% found this document useful (0 votes)
9 views25 pages

CTA ProblemsSolutions

Uploaded by

cleimoosila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views25 pages

CTA ProblemsSolutions

Uploaded by

cleimoosila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Nuno M.

Brites

COMPUTATIONAL TOOLS FOR ACTUARIES


Solutions to exercises

Master’s in Actuarial Science

Nuno M. Brites

[email protected]
Department of Mathematics
ISEG/ULisboa

2024–2025

Pg. 1
Nuno M. Brites

Pg. 2
Nuno M. Brites

Contents
1 Vectors 4
1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2 Matrices 9
2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

3 Data-frames 12
3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

4 Lists 14
4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

5 Functions 16
5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

6 Importing files 21
6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Pg. 3
Nuno M. Brites

1 Vectors
1.1
Compute the mean of:

(a) 𝑣 = (0, 1, 𝑁 𝐴, 2, 7).


(b) 𝑢 = (−𝐼𝑛𝑓, 0, 1, 𝑁 𝐴, 2, 7, 𝐼𝑛𝑓).
> # (a)
> v <- c(0, 1, NA, 2, 7)
> v
## [1] 0 1 NA 2 7
> # compute the mean without the NA
> mean(v, na.rm = TRUE)
## [1] 2.5
>
> # (b)
> u <- c(-Inf, 0, 1, NA, 2, 7, Inf)
> u
## [1] -Inf 0 1 NA 2 7 Inf
>
> # replace -Inf and Inf by NA caution as R replaces the values!
> u[u == Inf] <- NA
> u
## [1] -Inf 0 1 NA 2 7 NA
> u[u == -Inf] <- NA
> u
## [1] NA 0 1 NA 2 7 NA
> # compute the mean without the NA
> mean(u, na.rm = TRUE)
## [1] 2.5
>
>
> # Another way (keeping the original vector)
> u <- c(-Inf, 0, 1, NA, 2, 7, Inf)
> v <- replace(u, u == -Inf | u == Inf, NA)
> v
## [1] NA 0 1 NA 2 7 NA
>
> mean(v, na.rm = TRUE)
## [1] 2.5

1.2
Create:

Pg. 4
Nuno M. Brites

(a) a vector with values 𝑒𝑥 cos(𝑥) at 𝑥 = 3, 3.1, 3.2, … , 6.


> x <- seq(3, 6, by = 0.1)
> x
## [1] 3.0 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 4.0 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8
## [20] 4.9 5.0 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 6.0
> v <- (exp(x)) * cos(x)
> v
## [1] -19.885 -22.179 -24.491 -26.773 -28.969 -31.011 -32.820 -34.303 -35.357
## [10] -35.863 -35.688 -34.685 -32.694 -29.539 -25.033 -18.975 -11.157 -1.362
## [19] 10.632 25.047 42.099 61.997 84.929 111.062 140.525 173.406 209.733
## [28] 249.468 292.487 338.564 387.360
2 3 25
(b) a vector with values (2, 22 , 23 , … , 225 ) .
> x <- 1:25
> v <- (2^x)/x
> v
## [1] 2.000e+00 2.000e+00 2.667e+00 4.000e+00 6.400e+00 1.067e+01 1.829e+01
## [8] 3.200e+01 5.689e+01 1.024e+02 1.862e+02 3.413e+02 6.302e+02 1.170e+03
## [15] 2.185e+03 4.096e+03 7.710e+03 1.456e+04 2.759e+04 5.243e+04 9.986e+04
## [22] 1.907e+05 3.647e+05 6.991e+05 1.342e+06

1.3
Compute:

(a)
100
∑ 𝑗3 + 4𝑗2 .
𝑗=10

> j <- 10:100


> v <- (j^3) + 4 * j^2
> sum(v)
## [1] 26852735

(b)
25
2𝑗 3𝑗
∑ + 2.
𝑗=1
𝑗 𝑗
> i <- 1:25
> v <- (2^i)/i + (3^i)/(i^2)
> sum(v)
## [1] 2.129e+09

1.4
Create the vectors:

(a) (1, 2, 3, … , 19, 20).


Pg. 5
Nuno M. Brites

(b) (20, 19, … , 2, 1).


(c) (1, 2, 3, … , 19, 20, 19, 18, … , 2, 1).
(d) (1, 2, 3, 1, 2, 3, … , 1, 2, 3) where there are 10 occurrences of 1.
(e) (1, 1, … , 1, 2, 2, … , 2, 3, 3, … , 3) where there are 10 occurrences of 1, 20 occurrences of 2 and 30 occurrences of
3.
(f) (0.13 0.21 , 0.16 0.24 , … , 0.136 0.234 ).
> # (a)
> 1:20
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
>
> # (b)
> 20:1
## [1] 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
>
> # (c)
> c(1:20, 19:1)
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 19 18 17 16 15
## [26] 14 13 12 11 10 9 8 7 6 5 4 3 2 1
>
> # (d)
> rep(1:3, times = 10)
## [1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
>
> # (e)
> rep(1:3, times = c(10, 20, 30))
## [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3
## [39] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
>
> # (f)
> (0.1^seq(from = 3, to = 36, by = 3)) * (0.2^seq(from = 1, to = 34, by = 3))
## [1] 2.000e-04 1.600e-09 1.280e-14 1.024e-19 8.192e-25 6.554e-30 5.243e-35
## [8] 4.194e-40 3.355e-45 2.684e-50 2.147e-55 1.718e-60

1.5
Use the function paste to create the following character vector of length 20:

(”label 1”, ”label 2”, … , ”label 20”)

> paste("label", 1:20)


## [1] "label 1" "label 2" "label 3" "label 4" "label 5" "label 6"
## [7] "label 7" "label 8" "label 9" "label 10" "label 11" "label 12"
## [13] "label 13" "label 14" "label 15" "label 16" "label 17" "label 18"
## [19] "label 19" "label 20"

Pg. 6
Nuno M. Brites

1.6
Set the vector v2 equal to the following: “A” “A” “B” “B” “C” “C” “D” “D” “E” “E” (note the letters are all
uppercase).
> (v2 <- sort(rep(LETTERS[1:5], 2)))
## [1] "A" "A" "B" "B" "C" "C" "D" "D" "E" "E"

1.7
Set the vector v3 equal to the following: “a” “b” “c” “d” “e” “a” “b” “c” “d” “e” (note the letters are all lowercase)
> (v3 <- rep(letters[1:5], 2))
## [1] "a" "b" "c" "d" "e" "a" "b" "c" "d" "e"

1.8
Set the vector v4 equal to the words “dog” 10 times, “cat” 9 times, “fish” 6 times, and “fox” 1 time.
> v4 <- c(rep("dog", 10), rep("cat", 9), rep("fish", 6), rep("fox", 1))
> v4
## [1] "dog" "dog" "dog" "dog" "dog" "dog" "dog" "dog" "dog" "dog"
## [11] "cat" "cat" "cat" "cat" "cat" "cat" "cat" "cat" "cat" "fish"
## [21] "fish" "fish" "fish" "fish" "fish" "fox"

1.9
Run the following lines:
> set.seed(50)
> x <- sample(0:999, 250, replace = TRUE)
> y <- sample(0:999, 250, replace = TRUE)

(a) Explain the meaning of x and y.

Creates vectors x and y with length 250 sampled from a discrete uniform distribution U~(0,999).
> set.seed(50)
> x <- sample(0:999, 250, replace = TRUE)
> y <- sample(0:999, 250, replace = TRUE)

(b) Denote by 𝑥𝑖 and 𝑦𝑖 the entries of the vectors 𝑥 and 𝑦, respectively. Create vectors (𝑦2 − 𝑥1 , … , 𝑦𝑛 − 𝑥𝑛−1 )
sin(𝑦1 ) sin(𝑦𝑛−1 )
and ( cos(𝑥 ) , … , cos(𝑥 ) ) .
2 𝑛

> # (i)
> z1 <- y[-1] - x[-length(x)]
> head(z1)
## [1] -359 692 -724 40 -626 -719
>
> # (ii)
> z2 <- sin(y[-length(x)])/cos(x[-1])
Pg. 7
Nuno M. Brites

> head(z2)
## [1] -0.2512 -1.7145 -1.0205 1.9033 4.1197 0.4748

(c) Compute
𝑛−1
𝑒−𝑥𝑖+1

𝑖=1
𝑥𝑖 + 10
> sum(exp(-x[-1])/(x[-length(x)] + 10))
## [1] 5.029e-05

(d) Denote by 𝑥 the mean of the vector 𝑥 and compute

𝑛
∑ |𝑥𝑖 − 𝑥|̄ 1/2 .
𝑖=1

> sum(sqrt(abs(x - mean(x))))


## [1] 3767

(e) Extract the values of 𝑥 which correspond to the values of 𝑦 which are > 500.
> x[y > 500]
## [1] 367 819 706 903 17 761 439 481 795 624 988 473 568 161 926 518 852 593
## [19] 86 455 773 935 749 59 398 755 499 722 335 778 500 805 810 755 55 233
## [37] 125 332 440 811 385 765 470 526 591 345 610 221 646 261 640 477 206 388
## [55] 469 161 705 319 274 667 286 605 310 87 895 561 777 369 576 778 651 498
## [73] 963 961 212 777 31 201 324 387 770 258 232 924 438 25 376 218 665 708
## [91] 78 762 227 873 390 113 839 962 926 757 397 601 450 814 827 79 566 983
## [109] 3 317 523 402 680 512 954 687 449 398 211 139

(f) How many values of 𝑥 are above the mean of 𝑦?


> sum(x > mean(y))
## [1] 136

(g) How many values of 𝑥 are smaller than the minimum value of 𝑦?
> sum(x < min(y))
## [1] 0

(h) How many values of 𝑥 are divisible by 2?


> sum(x%%2 == 0)
## [1] 117

(i) Extract the 1st minimum value of 𝑥, the 4th minimum value of 𝑥, the 7th minimum value of 𝑥, etc.
> tmp <- sort(x)
> tmp[seq(from = 1, to = 250, by = 3)]
## [1] 3 17 31 46 59 78 87 98 113 125 150 160 180 201 212 218 232 239 251
## [20] 257 261 271 274 310 324 335 345 362 369 385 390 398 409 438 440 450 465 473
## [39] 481 498 504 518 526 563 576 593 601 609 618 640 648 656 665 678 692 706 722
## [58] 749 755 762 765 773 777 778 795 799 810 814 827 839 853 865 881 892 905 921
Pg. 8
Nuno M. Brites

## [77] 926 949 958 962 975 983 988 997

2 Matrices
2.1
Consider the matrix

1 1 3
⎡ ⎤
𝐴=⎢ 5 2 6⎥
⎢ ⎥
⎣−2 −1 −3⎦

(a) Verify that 𝐴3 = 0.


> a <- c(1, 1, 3, 5, 2, 6, -2, -1, -3)
> (A <- matrix(a, 3, 3, byrow = TRUE))
## [,1] [,2] [,3]
## [1,] 1 1 3
## [2,] 5 2 6
## [3,] -2 -1 -3
> A %*% A %*% A
## [,1] [,2] [,3]
## [1,] 0 0 0
## [2,] 0 0 0
## [3,] 0 0 0

(b) Replace the third column by the sum of column 1 and column 2.
> B <- A
> B[, 3] <- B[, 1] + B[, 2]
> B
## [,1] [,2] [,3]
## [1,] 1 1 2
## [2,] 5 2 7
## [3,] -2 -1 -3

2.2
Consider the matrix

Pg. 9
Nuno M. Brites

33 51 60
⎡ ⎤
⎢20 35 17⎥
⎢ ⎥
⎢15 27 24⎥
𝑀 =⎢ ⎥,
⎢15 21 28⎥
⎢ ⎥
⎢14 25 29⎥
⎢ ⎥
⎣10 53 24⎦

and replace even numbers by −1.


> m <- c(33, 51, 60, 20, 35, 17, 15, 27, 24, 15, 21, 28, 14, 25, 29, 10, 53, 24)
> (M <- matrix(m, 6, 3, byrow = TRUE))
## [,1] [,2] [,3]
## [1,] 33 51 60
## [2,] 20 35 17
## [3,] 15 27 24
## [4,] 15 21 28
## [5,] 14 25 29
## [6,] 10 53 24
> M[M%%2 == 0] <- -1
> M
## [,1] [,2] [,3]
## [1,] 33 51 -1
## [2,] -1 35 17
## [3,] 15 27 -1
## [4,] 15 21 -1
## [5,] -1 25 29
## [6,] -1 53 -1

2.3
Solve the linear system

⎧2𝑦 + 𝑥 − 𝑧 = 1
{
{
⎨2𝑧 − 𝑥 − 𝑦 = 0
{
{𝑥 + 1 + 𝑦 + 2𝑧 = 1

> a <- c(1, 2, -1, -1, -1, 2, 1, 1, 2)


> b <- c(1, 0, 0)
>
> (A <- matrix(a, 3, 3, byrow = TRUE))
## [,1] [,2] [,3]
## [1,] 1 2 -1
## [2,] -1 -1 2

Pg. 10
Nuno M. Brites

## [3,] 1 1 2
> (solve(A, b))
## [1] -1 1 0

2.4
Run the following lines:
> set.seed(75)
> M <- matrix(sample(10, size = 60, replace = TRUE), nrow = 6)

(a) Explain the result.

Creates a matrix 6x10 from a random vector taking values 1,…,10.


> set.seed(75)
> M <- matrix(sample(10, size = 60, replace = TRUE), nrow = 6)

(b) Find the number of entries in each row which are greater than 4.
> rowSums(M > 4)
## [1] 8 7 8 7 4 3

(c) Which rows contain exactly two occurrences of the number 7?


> which(rowSums(M == matrix(7, nrow = 6, ncol = 10)) == 2)
## [1] 1

(d) Denote by 𝑀𝑖,𝑗 the entries of the 𝑛 × 𝑚 matrix 𝑀 and compute the following means and sums of squares:

1
𝜇= ∑𝑀
𝑛 × 𝑚 𝑖,𝑗 𝑖,𝑗
1
𝜇𝑖 = ∑ 𝑀𝑖,𝑗 , 𝑖 = 1, … , 𝑛
𝑚 𝑗

𝑆𝑆1 = ∑(𝜇 − 𝜇𝑖 )2
𝑖

𝑆𝑆2 = ∑(𝑀𝑖,𝑗 − 𝜇𝑖 )2
𝑖,𝑗

𝑆𝑆3 = ∑(𝑀𝑖,𝑗 − 𝜇)2


𝑖,𝑗

> (Mu <- 1/(nrow(M) * ncol(M)) * sum(M))


## [1] 5.45
>
> (mu <- 1/ncol(M) * rowSums(M))
## [1] 5.8 5.1 6.4 6.6 4.8 4.0
>
> (SS1 <- sum((Mu - mu)^2))
## [1] 4.995
>

Pg. 11
Nuno M. Brites

> (SS2 <- sum((M - mu)^2))


## [1] 464.9
>
> (SS3 <- sum((M - Mu)^2))
## [1] 514.8

3 Data-frames
3.1
Install and load the package DAAG. Execute:

(a) Type library(help="DAAG") to get the information on this package.


> # install.packages('DAAG')
> library("DAAG")
> library(help = "DAAG")

(b) Consider the dataset carpriceand apply the convenient R command to check the structure of the dataset.
> str(carprice)
## 'data.frame': 48 obs. of 9 variables:
## $ Type : Factor w/ 6 levels "Compact","Large",..: 3 2 2 3 2 3 1 1 5 3 ...
## $ Min.Price : num 14.2 19.9 22.6 26.3 33 37.5 8.5 11.4 13.4 13.4 ...
## $ Price : num 15.7 20.8 23.7 26.3 34.7 40.1 13.4 11.4 15.1 15.9 ...
## $ Max.Price : num 17.3 21.7 24.9 26.3 36.3 42.7 18.3 11.4 16.8 18.4 ...
## $ Range.Price: num 3.1 1.8 2.3 0 3.3 5.2 9.8 0 3.4 5 ...
## $ RoughRange : num 3.09 1.79 2.31 -0.01 3.3 5.18 9.8 -0.01 3.38 5.01 ...
## $ gpm100 : Named num 3.8 4.2 4.9 4.3 4.9 4.9 3.3 3.4 4.2 4 ...
## ..- attr(*, "names")= chr [1:48] "6" "7" "8" "9" ...
## $ MPG.city : num 22 19 16 19 16 16 25 25 19 21 ...
## $ MPG.highway: num 31 28 25 27 25 25 36 34 28 29 ...

(c) Set a name for carprice, say x.


> x <- carprice

(d) Explain the meaning of table(x$Type).


> table(x$Type) # Absolute frequencies
##
## Compact Large Midsize Small Sporty Van
## 7 11 10 7 8 5

(e) Replace all column names.


> colnames(x) <- c("Car_type", "Price_min", "Price", "Price_max", "Price_range", "Real_price_range",
+ "Consumption", "City_consumption", "HighWay_consumption")

(f) Compute the mean, variance, standard deviation, range, maximum and minimum of the maximum price
Pg. 12
Nuno M. Brites

variable.
> attach(x)
> (some.stats <- c(mean(Price_max), var(Price_max), sd(Price_max), range(Price_max),
+ max(Price_max), min(Price_max)))
## [1] 20.627 67.279 8.202 7.900 42.700 42.700 7.900

(g) Drop all the rows with maximum price higher than 24.8 m.u.
> y <- x[Price_max <= 24.8, ]
> head(y)
## Car_type Price_min Price Price_max Price_range Real_price_range Consumption
## 6 Midsize 14.2 15.7 17.3 3.1 3.09 3.8
## 7 Large 19.9 20.8 21.7 1.8 1.79 4.2
## 12 Compact 8.5 13.4 18.3 9.8 9.80 3.3
## 13 Compact 11.4 11.4 11.4 0.0 -0.01 3.4
## 14 Sporty 13.4 15.1 16.8 3.4 3.38 4.2
## 15 Midsize 13.4 15.9 18.4 5.0 5.01 4.0
## City_consumption HighWay_consumption
## 6 22 31
## 7 19 28
## 12 25 36
## 13 25 34
## 14 19 28
## 15 21 29

(h) Drop all the rows with minimum price lower than 14.0 m.u.
> z <- x[Price_min >= 14, ]
> head(z)
## Car_type Price_min Price Price_max Price_range Real_price_range Consumption
## 6 Midsize 14.2 15.7 17.3 3.1 3.09 3.8
## 7 Large 19.9 20.8 21.7 1.8 1.79 4.2
## 8 Large 22.6 23.7 24.9 2.3 2.31 4.9
## 9 Midsize 26.3 26.3 26.3 0.0 -0.01 4.3
## 10 Large 33.0 34.7 36.3 3.3 3.30 4.9
## 11 Midsize 37.5 40.1 42.7 5.2 5.18 4.9
## City_consumption HighWay_consumption
## 6 22 31
## 7 19 28
## 8 16 25
## 9 19 27
## 10 16 25
## 11 16 25

3.2
Create a list with information about 3 workers as follows:
Pg. 13
Nuno M. Brites

(a) The list should have 4 vectors as components: name, age, gender and a boolean variable (it assumes values 0
or 1 that defines whether the person works or not).
> name <- c("Rachel", "Monica", "Chandler")
> age <- c(25, 26, 26)
> gender <- factor(c("F", "F", "M"))
> work <- c(1, 0, 1)
>
> friends.ls <- list(Name = name, Age = age, Gender = gender, Work = work)
> friends.ls
## $Name
## [1] "Rachel" "Monica" "Chandler"
##
## $Age
## [1] 25 26 26
##
## $Gender
## [1] F F M
## Levels: F M
##
## $Work
## [1] 1 0 1

(b) Create a data frame with the information from the previous list.
> friends <- data.frame(friends.ls)
> friends
## Name Age Gender Work
## 1 Rachel 25 F 1
## 2 Monica 26 F 0
## 3 Chandler 26 M 1

(c) Add a vector to the previous data frame with information about the person’s job.
> friends <- data.frame(friends, Job = factor(c("Sales manager", "Unemployed", "Accounter")))

(d) Compute the mean, variance, standard deviation, range, maximum and minimum of the age.
> attach(friends)
> (some.stats <- c(mean(Age), var(Age), sd(Age), range(Age), max(Age), min(Age)))
## [1] 25.6667 0.3333 0.5774 25.0000 26.0000 26.0000 25.0000

4 Lists
4.1
Run the following lines:

Pg. 14
Nuno M. Brites

> set.seed(75)
> x <- sample(10, size = 10, replace = TRUE)
> y <- sample(10, size = 10, replace = TRUE)

(a) Create a list whose elements are the vectors 𝑥 and 𝑦 with names “sample1” and “sample2”, respectively.
(b) Create a list with the mean and standard deviation of each sample.
> set.seed(75)
> x <- sample(10, size = 10, replace = TRUE)
> y <- sample(10, size = 10, replace = TRUE)
>
> # (a)
> list(sample1 = x, sample2 = y)
## $sample1
## [1] 8 9 5 9 7 9 8 5 1 3
##
## $sample2
## [1] 3 3 8 2 10 1 3 3 7 6
>
> # (b)
> list(sample1 = list(mean = mean(x), sd = sd(x)), sample2 = list(mean = mean(y), sd = sd(y)))
## $sample1
## $sample1$mean
## [1] 6.4
##
## $sample1$sd
## [1] 2.797
##
##
## $sample2
## $sample2$mean
## [1] 4.6
##
## $sample2$sd
## [1] 2.951

4.2
Create a list:

(a) with years from 2005 to 2016, 12 months and 31 days.


(b) replace year by c(2000:2010).
(c) delete the value 4 of the month.
> # (a)
> Date <- list(year = 2005:2016, month = 1:12, day = 1:31)

Pg. 15
Nuno M. Brites

> Date
## $year
## [1] 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
##
## $month
## [1] 1 2 3 4 5 6 7 8 9 10 11 12
##
## $day
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
## [26] 26 27 28 29 30 31
>
> # (b)
> Date$year <- 2000:2010
> Date
## $year
## [1] 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
##
## $month
## [1] 1 2 3 4 5 6 7 8 9 10 11 12
##
## $day
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
## [26] 26 27 28 29 30 31
>
> # (c)
> Date$month <- Date$month[-4]
> Date
## $year
## [1] 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
##
## $month
## [1] 1 2 3 5 6 7 8 9 10 11 12
##
## $day
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
## [26] 26 27 28 29 30 31

5 Functions
5.1
Write a function called my_add that adds two numbers (x and y) together and returns the results. Run
my_add(5,7).

Pg. 16
Nuno M. Brites

> my_add <- function(x, y) {


+ return(x + y)
+ }
>
> my_add(5, 7)
## [1] 12

5.2
Copy the function my_add above and add an error message that returns “x and y must be numbers” if x or y are
not both numbers.
> my_add <- function(x, y) {
+ if (is.numeric(x) & is.numeric(y))
+ return(x + y) else print("x and y must be numbers")
+ }
> my_add(5, 12)
## [1] 17
>
> my_add(5, letters[1])
## [1] "x and y must be numbers"

5.3
(a) Write a function that accepts a numerical vector (𝑥1 , 𝑥2 , … , 𝑥𝑛 ) as argument and returns the vector

𝑥22 𝑥𝑛
(𝑥1 , ,…, 𝑛).
2 𝑛

Run for 1:4.


> f.a <- function(x) {
+ n <- length(x)
+ (x^(1:n))/(1:n)
+ }
>
> f.a(1:4)
## [1] 1 2 9 64

(b) Write a function that accepts a single number 𝑥 and a positive integer 𝑛 and returns the sum

𝑥2 𝑥3 𝑥𝑛
1+𝑥+ + +⋯+ .
2 3 𝑛

Run for 𝑥 = 2 and 𝑛 = 5.
> f.b <- function(x, n) {
+ return(1 + sum((x^(1:n))/(1:n)))
+ }
Pg. 17
Nuno M. Brites

>
> f.b(sqrt(2), 5)
## [1] 6.488

(c) Write a function which takes a matrix as single argument and returns a matrix which is the same as the
function argument but every odd entry is doubled. Run for matrix(sample(1:10),2,5)
> f.c <- function(m) {
+ m * (1 + m%%2)
+ }
>
> M <- matrix(sample(1:100), 2, 5)
## Warning in matrix(sample(1:100), 2, 5): data length differs from size of
## matrix: [100 != 2 x 5]
> M
## [,1] [,2] [,3] [,4] [,5]
## [1,] 50 20 39 21 95
## [2,] 65 48 79 6 86
> f.c(M)
## [,1] [,2] [,3] [,4] [,5]
## [1,] 50 20 78 42 190
## [2,] 130 48 158 6 86

(d) Write a function to convert the temperature measured in Celsius (°C) to Fahrenheit (°F). Check that
f.d(0) = 32 and f.d(-40) = -40.
> f.d <- function(cel) {
+ 9/5 * cel + 32
+ }
>
> f.d(c(0, -40))
## [1] 32 -40

(e) Write a function that takes a single integer argument 𝑛 and returns the sum of its divisors, e.g., if 𝑛 = 6,
then the function returns 1 + 2 + 3 + 6.
> f.e <- function(n) {
+ sum(which(n%%(1:n) == 0))
+ }
>
> f.e(6)
## [1] 12

(f) Write a function that takes arguments 𝑎, 𝑏, 𝑐 ∈ ℝ and returns the roots of the polynomial 𝑎𝑥2 + 𝑏𝑥 + 𝑐. The
output should be a list containing the two roots. In case the roots are complex conjugated, the output of
each root should be a list of its real and imaginary parts. Find the solutions of 𝑥2 − 4𝑥 + 4 = 0 and
3𝑥2 − 𝑥 + 4 = 0.

Pg. 18
Nuno M. Brites

> f.f <- function(a, b, c) {


+ if (a == 0) {
+ if (b == 0) {
+ if (c == 0) {
+ return(list("zero polynomial, infinite solutions"))
+ } else {
+ return(list("Impossible, no solutions"))
+ }
+ } else {
+ return(list(x = -c/b))
+ }
+ } else {
+ delta = b^2 - 4 * a * c
+ if (delta >= 0) {
+ return(list(x1 = (-b + sqrt(delta))/(2 * a), x2 = (-b - sqrt(delta))/(2 *
+ a)))
+ } else {
+ return(list(x1 = list(real = -b/(2 * a), img = sqrt(-delta)/(2 * a)),
+ x1 = list(real = -b/(2 * a), img = -sqrt(-delta)/(2 * a))))
+ }
+ }
+ }
>
> f.f(1, -4, 4)
## $x1
## [1] 2
##
## $x2
## [1] 2
>
> f.f(3, -1, 4)
## $x1
## $x1$real
## [1] 0.1667
##
## $x1$img
## [1] 1.143
##
##
## $x1
## $x1$real
## [1] 0.1667
##
## $x1$img
Pg. 19
Nuno M. Brites

## [1] -1.143

5.4
Consider the function


{2𝑒−2𝑥 , 𝑥 ≥ 0
𝑓(𝑥) = ⎨ .
{
⎩0, 𝑥<0

(a) Show that 𝑓 is a density probability function (dpf).


> f <- function(x) ifelse(x < 0, 0, 2 * exp(-2 * x))
> integrate(f, -Inf, Inf)
## 1 with absolute error < 5e-07

(b) Let 𝑋 be a r.v. with dpf 𝑓 and compute 𝑃 (𝑋 > 1). Show the value with 2 decimal places.
> round(integrate(f, 1, Inf)$value, digits = 2)
## [1] 0.14

(c) Compute 𝑃 (0.3 < 𝑋 < 0.7). Show the value with 3 decimal places.
> round(integrate(f, 0.3, 0.7)$value, digits = 3)
## [1] 0.302

(d) Compute 𝐸[𝑋]. Show the value with 1 decimal place.


> f1 <- function(x) x * f(x)
> round(integrate(f1, 0, Inf)$value, digits = 1)
## [1] 0.5

5.5
Plot a graphic of 𝑓(𝑥) = 1 − 𝑥1 𝑠𝑖𝑛(𝑥) for 0 < 𝑥 < 5 and for 0 < 𝑥 < 50.
> f <- function(x) {
+ 1 - (1/x) * sin(x)
+ }
> par(mfrow = c(1, 2))
> plot(f, 0, 5, xlim = c(0, 5), ylim = c(0, 1.5))
> plot(f, 0, 50, xlim = c(0, 50), ylim = c(0, 1.5))

Pg. 20
Nuno M. Brites

1.0

1.0
f

f
0.0

0.0
0 1 2 3 4 5 0 10 20 30 40 50

x x

5.6
√ 2 2)
Plot a graphic of 𝑓(𝑥, 𝑦) = 10 sin(√𝑥2𝑥+𝑦+𝑦2 for 1 < 𝑥 < 20, 1 < 𝑦 < 20 and 𝑧 =outer(x,y,g). By the way, run
outer(0:9, 0:9, "*") and outer(0:9, 0:9, "+").
> f <- function(x, y) {
+ 10 * sin(sqrt(x^2 + y^2))/sqrt(x^2 + y^2)
+ }
> x <- 1:20
> y <- 1:20
> z <- outer(x, y, f)
> z[is.na(z)] <- 1
> persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "blue")
z

Change the parameters and run again.

6 Importing files
6.1
Consider the file life.csv describing the life expectancy of males and females born in the UK. Execute:

(a) Save the file to your computer and import the data to R. Also display the dimensions, column names and a
summary of the data frame.

Pg. 21
Nuno M. Brites

> life <- read.csv("InFiles/life.csv", header = TRUE)


> dim(life)
## [1] 243 4
> colnames(life)
## [1] "Age" "Male.babies" "Female.babies" "Annotations"
> summary(life)
## Age Male.babies Female.babies Annotations
## Min. :1841 Min. :36.8 Min. :38.5 Length:243
## 1st Qu.:1902 1st Qu.:45.9 1st Qu.:49.9 Class :character
## Median :1962 Median :68.0 Median :73.9 Mode :character
## Mean :1962 Mean :64.8 Mean :68.7
## 3rd Qu.:2022 3rd Qu.:81.9 3rd Qu.:85.5
## Max. :2083 Max. :88.9 Max. :92.0

(b) Determine the number of years between 1841 and 1900 where male life expectancy was less than 40.
> sum(life$Male.babies < 40 & life$Age >= 1841 & life$Age <= 1900)
## [1] 20

(c) Plot how the female life expectancy changes over the years (given in the age column). Add labels to axis of
the plot and join the points by straight lines.
> attach(life)
## The following object is masked from friends:
##
## Age
> plot(Age, Female.babies, type = "l", ylab = "Female life expectancy ", xlab = "Year",
+ main = "Female life expectancy vs. Year")

Female life expectancy vs. Year


Female life expectancy

80
60
40

1850 1900 1950 2000 2050

Year
> # Or...
>
> plot(Female.babies ~ Age, life, type = "l", ylab = "Female life expectancy ", xlab = "Year",
+ main = "Female life expectancy vs. Year")

Pg. 22
Nuno M. Brites

Female life expectancy vs. Year

Female life expectancy

80
60
40

1850 1900 1950 2000 2050

Year
(d) Plot the relationship between male and female life expectancy as a scatter plot. e.g. male on the x axis and
female on the y axis. Add labels to the axis and a title.

(e) Add a linear trend to the previous scatter plot.


> # (d)
> plot(Male.babies, Female.babies, ylab = "Female", xlab = "Male", main = "Male vs. Female")
> # (e)
> abline(lm(Female.babies ~ Male.babies, life), col = 2)

Male vs. Female


80
Female

60
40

40 50 60 70 80 90

Male
>
> # Or
>
> # (d)
> plot(Female.babies ~ Male.babies, life, ylab = "Female", xlab = "Male", main = "Male vs. Female")
> # (e)
> abline(lm(Female.babies ~ Male.babies, life), col = 2)

Pg. 23
Nuno M. Brites

Male vs. Female

80
Female

60
40

40 50 60 70 80 90

Male
(f) Create a histogram and a boxplot of the male and female life expectancy. Use 25 breaks.
> par(mfrow = c(1, 2))
> hist(Male.babies, breaks = 25, col = 4)
> hist(Female.babies, breaks = 25, col = 3)

Histogram of Male.babies Histogram of Female.babies


20

20
15

15
Frequency

Frequency
10

10
5

5
0

40 60 80 40 60 80

Male.babies Female.babies
> par(mfrow = c(1, 1))
> boxplot(Male.babies, Female.babies, col = c(3, 4))

Pg. 24
Nuno M. Brites

90
80
70
60
50
40

1 2

Copyright: All rights reserved. No parts of the content of this file may be reproduced or
distributed without the prior written permission of the author. Without prior written permission,
it is not permitted to copy, download or reproduce the text, code, and images in any way
whatsoever.

2024–2025 | Nuno M. Brites | [email protected]

Pg. 25

You might also like