Repository navigation
Expand file tree
/
Copy pathTutorial_1-R_solution.Rmd
More file actions
447 lines (375 loc) · 10.6 KB
/
Copy pathTutorial_1-R_solution.Rmd
File metadata and controls
447 lines (375 loc) · 10.6 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
---
title: "Applied Statistics with R (STAT 215)"
subtitle: "Tutorial 1: The R Language"
author:
- "Ziling Ma"
- "ziling.ma@kaust.edu.sa"
date: "September 29, 2024"
output:
prettydoc::html_pretty:
theme: leonids
highlight: vignette
toc: true
number_sections: true
---
<!-- <style type="text/css"> -->
<!-- body{ -->
<!-- font-size: 10pt; -->
<!-- } -->
<!-- </style> -->
# Assigning Objects {#Ex1}
a. Create an object that stores the value $32 × \frac{41}{8}$.
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
a <- 32 * 41 / 8
print(a)
# or you can simply use 'a'
```
</details>
b. Overwrite your object in (a) by itself divided by $2.33$. Print the result to the console.
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
# Notice here we would like to overwrite
a <- a / 2.33
# check value of a
a
```
</details>
c. Create a new object with the value $−8.2 × 10^{−3}$.
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
b <- -8.2 * 10^(-3)
```
</details>
d. Print directly to the console the result of multiplying (b) by (c).
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
(a * b)
```
</details>
<a href="#Ex1">Back to</a> <a href="#top">top</a>
# Vectors {#Ex2}
a. Create and store a sequence of values from 5 to −11 that progresses in steps of 0.3.
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
sq <- seq(5,-11,by=-0.3)
sq
```
</details>
b. Overwrite the object from (a) using the same sequence with the order reversed.
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
sq <- rev(sq)
sq
```
</details>
c. Repeat the vector c(-1,3,-5,7,-9) twice, with each element repeated 10 times, and store the result. Display the result sorted from largest to smallest.
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
# Create the vector
vec <- c(-1, 3, -5, 7, -9)
# Repeat the vector twice, with each element repeated 10 times
repeated_vec <- rep(vec, each = 10, times = 2)
# Sort the result from largest to smallest
sorted_vec <- sort(repeated_vec, decreasing = TRUE)
# Print the sorted result
sorted_vec
```
</details>
d. Extract the first and last elements of your vector from (b), storing them as a new object.
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
# We name the vector 'sq'
# Extract the first element of 'sq', notice in R (also in Matlab), we start from 1 instead of 0 like in Python
sq[1]
# Extract the last element, same as in Python you use -1, in Matlab you use 'end'
sq[length(sq)]
```
</details>
<a href="#Ex1">Back to</a> <a href="#top">top</a>
# Matrix operations {#Ex3}
In `R`, use just one line of code to create the following mtrices and assign them to the variables `W`, and `X`, respectively.
\[
W=\begin{pmatrix}
1 & 4 & 7 \\
2 & 5 & 8 \\
3 & 6 & 9
\end{pmatrix};
X = \begin{pmatrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{pmatrix};
\]
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
(W <- matrix(data = 1:9, nrow = 3, ncol = 3, byrow = FALSE))
```
```{r}
(X <- matrix(data = 1:9, nrow = 3, ncol = 3, byrow = TRUE))
```
</details>
Also, compute $W\odot X$ and $W\cdot X$, such that $\odot$ represents the element-wise multiplication and $\cdot$ represents matrix multiplication.
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
W * X
```
```{r}
W %*% X
```
</details>
Given a matrix Y, where
```{r}
Y <- matrix(c(2,3,1,4),nrow = 2)
Y
```
How can you compute the inverse matrix of Y?
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
solve(Y)
```
</details>
<a href="#Ex1">Back to</a> <a href="#top">top</a>
# Matrix and functions {#Ex4}
Create a matrix $A\in\mathbb R^{3\times3}$, such that
\[
a_{ij} = i + j,\quad\forall i,j.
\]
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
A <- matrix(nrow = 3, ncol = 3)
for(i in 1:3) {
for(j in 1:3) {
A[i,j] <- i + j
}
}
A
```
</details>
Also, create $B\in \mathbb R^{3\times3}$, such that
\[
b_{ij}=\begin{cases}
\text{TRUE}, & a_{ij} \text{ is even}, \\
\text{FALSE}, &\text{otherwise}.
\end{cases}
\]
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
fB <- function(b) return(!as.logical(b %% 2))
(B <- matrix(fB(A), nrow = 3, ncol = 3))
```
</details>
c. Create $C\in \mathbb R^{3\times3}$, such that
\[
c_{ij}=\begin{cases}
1, & a_{ij} \in \{1,2,3\}, \\
0, &\text{otherwise}.
\end{cases}
\]
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
fC <- function(c) return(as.numeric(c %in% c(1,2,3)))
(C <- apply(A, MARGIN = c(1,2), fC))
```
</details>
d. Confirm the dimensions of the matrix from (a) are $2 × 3$ if you remove any one row.
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
A_modified <- A[-1, ]
A_modified
dim(A_modified)
```
</details>
<a href="#Ex1">Back to</a> <a href="#top">top</a>
# Recursive functions 1 {#Ex5}
Write a function for computing $f(n)=n!,\ (n\in \mathbb N)$. Print the 10 first numbers from the sequence $f$.
Also, for $n=10$, compare your result with the `gamma()` function from `R` (recall that, for any positive integer $n$, $\Gamma(n) = (n-1)!$).
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
factorial <- function(n){
if((n == 0) || (n == 1))
return(1)
else
return (n * factorial(n-1))
}
sapply(0:9, FUN = factorial)
cat("Gamma(10) =", gamma(10), "; 9! =", factorial(9))
```
</details>
<a href="#Ex1">Back to</a> <a href="#top">top</a>
# Graph function {#Ex6}
Use the functions `outer` y `persp` to graph the following functions\n\n")
$$f(x, y) = 1 - exp(-1 / (x^2 + y^2)), \text{for}\: x, y ∈ [-5, 5]$$
$$f(x, y) = sin(x)cos(y), \text{for}\: x, y ∈ [-\pi/2, \pi/2]$$
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
# Define the range for x and y
x <- seq(-5, 5, length = 50)
y <- seq(-5, 5, length = 50)
# Define the function
f1 <- function(x, y) {
1 - exp(-1 / (x^2 + y^2))
}
# Create a grid using outer
z1 <- outer(x, y, f1)
# Plot using persp
persp(x, y, z1, col = "salmon2",
xlab = "X", ylab = "Y", zlab = "f(x, y)",
main = "Graph of f(x, y) = 1 - exp(-1/(x^2 + y^2))")
# Notice, you can adjust the theta and phi values in persp() if you want a different viewing angle, for example
persp(x, y, z1, theta = 30, phi = 30,col = "salmon2",
xlab = "X", ylab = "Y", zlab = "f(x, y)",
main = "Graph of f(x, y) = 1 - exp(-1/(x^2 + y^2))")
```
</details>
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
# Define the range for x and y
x2 <- seq(-pi/2, pi/2, length = 100)
y2 <- seq(-pi/2, pi/2, length = 100)
# Define the function
f2 <- function(x, y) {
sin(x) * cos(y)
}
# Create a grid using outer
z2 <- outer(x2, y2, f2)
# Plot using persp
persp(x2, y2, z2, theta = 30, phi = 30, col = "lightgreen",
xlab = "X", ylab = "Y", zlab = "f(x, y)",
main = "Graph of f(x, y) = sin(x) * cos(y)")
```
</details>
<a href="#Ex1">Back to</a> <a href="#top">top</a>
# Linear regression {#Ex7}
Suppose that we model the height of male teenagers as
\[
\mathrm{height}_i = \beta_0 + \beta_1 \cdot \mathrm{age}_i + \epsilon_i,\ \text{s.t. } \epsilon_i \sim \mathcal N\left(0, \sigma^2\right).
\]
Now, for a random sample of size $n=20$, we want to estimate $\boldsymbol \beta = (\beta_0,\beta_1)^\intercal$ as
\[
\boldsymbol \beta = (X^\intercal X)^{-1} X^{\intercal} \boldsymbol y,
\]
where
\[
X = \begin{pmatrix}
1 & \textrm{age}_1 \\
\vdots & \vdots \\
1 & \textrm{age}_{20}
\end{pmatrix},\quad
\boldsymbol y = \begin{pmatrix}
\textrm{height}_1 \\
\vdots\\
\textrm{height}_{20}
\end{pmatrix}.
\]
Compute $\hat {\boldsymbol \beta}$ and plot $\hat {\boldsymbol y} =X\hat {\boldsymbol \beta}$. For this exercise, generate the data set using the following code:
```{r}
set.seed(999)
beta.0 <- 140
beta.1 <- 2
ages <- sample(x = 12:18, size = 20, replace = TRUE)
heights <- round(x = beta.0 + beta.1 * ages + rnorm(n = 10, mean = 0, sd = 2),
digits = 2)
data <- data.frame(heights = heights, ages = ages)
```
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
X <- cbind(rep(x = 1, times = 20), data$ages)
y <- as.matrix(data$heights)
(beta_hat <- solve(t(X) %*% X) %*% t(X) %*% y)
y_hat <- X %*% beta_hat
```
```{r}
plot(x = data$ages, y = data$heights, xlab = "Age", ylab = "Height (cm)")
par(new = TRUE)
plot(x = data$ages, y = y_hat, type = "b" , col = "red", axes = FALSE, xlab = "", ylab = "")
summary(lm(heights ~ ages, data))
```
</details>
<a href="#Ex1">Back to</a> <a href="#top">top</a>
# `R Markdown` and `R Sweave`
* Very elegent and powerful tools to use with `Rstudio`.
* Work very well for homework, reports, presentations, etc.
* `R Markdown` is mainly for generating `.html` files though it can also generate `.pdf` files and many more (this file is generated by `R Markdown`).
* `R Sweave` is like $\LaTeX$ but with `R` chunks within. It generates standard `.pdf` files.
# A fun exercise if you would like to try
## Recursive functions
Create 3 `N`-element row vectors `p`, `q`, and `r`:
\[
\begin{cases}
\mathtt{p}: &\text{prime number sequence},\\
\mathtt{q}: &\text{Fibonacci sequence},\\
\mathtt{r}: &r_n=\lfloor\sqrt{n\pi}\rfloor.
\end{cases}
\]
Do NOT compute the terms manually (write functions!).
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
prime_seq <- function(n, i = 1, primes = c()){
if(length(primes) < n) {
if (i == 2 || sum(as.numeric(i %% (1:i) == 0)) == 2){
prime_seq(n = n, i = i + 1, primes = c(primes, i))
}else{
prime_seq(n = n, i = i + 1, primes = primes)
}
}else{
return(primes)
}
}
fibonacci_seq <- function (n){
fib = c()
for (i in 1:n){
if (i == 1){
fib <- c(fib, 0)
}else if(i == 2){
fib <- c(fib, 1)
}else{
fib <- c(fib, fib[i - 1] + fib[i - 2])
}
}
return(fib)
}
r_seq <- function(n) return(floor(sqrt((1:n) * pi)))
N <- 5
(p <- prime_seq(n = N))
(q <- fibonacci_seq(n = N))
(r <- r_seq(N))
```
</details>
Also, create matrices:
\[
A=\begin{pmatrix}
\mathtt p \\ \mathtt q \\ \mathtt r
\end{pmatrix},
B=\begin{pmatrix}
\mathtt p^\intercal & \mathtt q^\intercal & \mathtt r^\intercal
\end{pmatrix}
\]
<details>
<summary><span style="color:blue">Click for answer</span></summary>
```{r}
(A <- rbind(p, q, r))
(B <- cbind(p, q, r))
```
</details>
<a href="#Ex1">Back to</a> <a href="#top">top</a>