-
Notifications
You must be signed in to change notification settings - Fork 2
/
section3.Rmd
871 lines (690 loc) · 21.3 KB
/
section3.Rmd
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
---
title: 'Introduction to R^[`r library(r2symbols) ; format(paste(symbol("copyright") , " - Wim R.M. Cardoen, 2022 - The content can neither be copied nor distributed without the **explicit** permission of the author."))`]'
subtitle: 'Part 3: Matrices/Arrays & Special Data Types'
author: "Wim R.M. Cardoen"
date: "Last updated: `r format(Sys.time(), ' %2m/%2d/%Y @ %2H:%2M:%2S')`"
output:
pdf_document:
highlight: tango
df_print: tibble
toc: true
toc_depth: 5
number_sections: True
extra_dependencies:
- amsfonts
- amsmath
- xcolor
- hyperref
bibliography: [latex/intro.bib]
csl: https://raw.githubusercontent.com/citation-style-language/styles/master/research-institute-for-nature-and-forest.csl
urlcolor: violet
---
\newpage
$\texttt{"It is my experience that proofs involving matrices can be}\newline
\texttt{shortened by 50\% if one throws the matrices out" (Emil Artin)}$
# Matrices & Arrays
Matrices and arrays are $\textbf{homogeneous atomic vectors}$ with$\newline$
an $\textbf{extra}$ attribute: dimension
By default, the elements are stored in a $\textbf{column-major}$ fashion. (cfr. $\textbf{Fortran}$).$\newline$
However, we can store the elements in $\textbf{row-major}$ order (cfr. $\textbf{C}$) as well.
## Creation of matrices
Matrices can be created in different ways:
* use of the $\textcolor{blue}{\textbf{matrix()}}$ function
* use of $\textcolor{blue}{\textbf{rbind()}}$/$\textcolor{blue}{\textbf{cbind()}}$
* set the $\textcolor{blue}{\textbf{attributes()}}$ of a vector
* special functions like e.g. $\textcolor{blue}{\textbf{diag()}}$
### Examples
* use of the $\textcolor{blue}{\textbf{matrix()}}$ function:
The $\textcolor{blue}{\textbf{matrix()}}$ function creates a matrix based on a vector.$\newline$
By default, the elements are stored in a $\textbf{column-major}$ fashion.
The use of the flag $\texttt{byrow=TRUE}$ will store the data in a $\textbf{row-major}$ fashion.
```{R, echo=TRUE, comment=''}
A <- matrix(data=1:10, nrow=2) # Column-major (like Fortran)
A
B <- matrix(data=c(2,3,893,0.17), nrow=2, ncol=2)
B
```
$\newline$
```{R, echo=TRUE, comment=''}
C <- matrix(data=1:10, nrow=2, byrow=TRUE) # Row-major (like C, C++)
C
```
$\newline$
* use of the $\textcolor{blue}{\textbf{rbind()}}$/$\textcolor{blue}{\textbf{cbind()}}$ functions:
- $\textcolor{blue}{\textbf{rbind()}}$: Bind several vectors (as rows) into a matrix.
- $\textcolor{blue}{\textbf{cbind()}}$: Bind several vectors (as columns) into a matrix.
```{R, echo=TRUE, comment=''}
A <- rbind(1:10,11:20)
A
typeof(A)
class(A)
```
$\newline$
```{R, echo=TRUE, comment=''}
B <- cbind(1:5,6:10,11:15)
B
class(B)
```
### Matrices: vectors with a non-NULL dim attribute
The $\textbf{fundamental}$ difference between an $\texttt{R}$ vector and matrix is
the presence (in the case of matrices) of a non $\texttt{NULL}$
$\textcolor{blue}{\textbf{dim}}$ attribute.
We can easily convert a vector into a matrix by setting the dimensions of the vector:
\begin{itemize}
\item through the $\textcolor{blue}{\textbf{dim()}}$ function.
\item through the $\textcolor{blue}{\textbf{attr()}}$ function.
\end{itemize}
The inverse can be done as well by setting the $\textcolor{blue}{\textbf{dim}}$ attribute
of matrix to $\texttt{NULL}$.
```{R, echo=TRUE, comment=''}
A <- 1:10
typeof(A)
class(A)
dim(A)
```
$\newline$
```{R, echo=TRUE, comment=''}
# Matrix
B <- matrix(1:10,nrow=2,ncol=5,byrow=TRUE)
typeof(B)
class(B)
dim(B)
```
$\newline$
```{R, echo=TRUE, comment=''}
# Vector
A <- 1:10
A
dim(A)
typeof(A)
class(A)
```
$\newline \newline$
```{R, echo=TRUE, comment=''}
# OPTION I: Using the dim function transform a vector into a matrix
dim(A) <- c(2,5)
A
dim(A)
typeof(A)
class(A)
```
$\newline$
```{R, echo=TRUE, comment=''}
# Converting the matrix back to a vector
dim(A) <- NULL
dim(A)
typeof(A)
class(A)
```
$\newline \newline$
```{R, echo=TRUE, comment=''}
# Option II: More general way
# Convert vector into a matrix
A <- 1:8
A
class(A)
attr(A,'dim') <- c(2,4)
A
class(A)
```
$\newline$
```{R, echo=TRUE, comment=''}
# Convert matrix into a vector.
attr(A, 'dim') <- NULL
A
class(A)
```
## Retrieving elements/subsetting
Matrices (and arrays) can be subsetted in different ways:
* use an $\textbf{index}$ for each dimension, where the dimensions are comma-separated
- If an $\textbf{index}$ for a dimension is $\textbf{omitted}$: $\newline$
consider all dimensions (may lead to reduction of the dimension)
- $\textbf{but}$ you can use $\textcolor{blue}{\textbf{drop=FALSE}}$ to prevent dimensionality reduction.
* use another $\textbf{vector}$ (can be either linear or a vector for each dimension)
* by using another $\textbf{matrix}$.
### Examples
* Use of $\textbf{indices}$:
```{R, echo=TRUE, comment=''}
A <- matrix(1:30, nrow=6, ncol=5)
A
```
$\newline$
```{R, echo=TRUE, comment=''}
A[3,4]
A[6,2]
```
$\newline$
```{R, echo=TRUE, comment=''}
x1 <- A[2,]
x1
dim(x1)
```
$\newline$
```{R, echo=TRUE, comment=''}
x2 <- A[,3]
x2
dim(x2)
```
$\newline$
The flag $\textcolor{blue}{\textbf{drop=FALSE}}$ can be used to prevent dimensionality reduction
```{R, echo=TRUE, comment=''}
y1 <- A[2,,drop=FALSE]
y1
dim(y1)
```
$\newline$
```{R, echo=TRUE, comment=''}
y2 <- A[,3,drop=FALSE]
y2
dim(y2)
```
* Use of $\textbf{vector(s)}$:
```{R, echo=TRUE, comment=''}
A
```
$\newline$
```{R, echo=TRUE, comment=''}
x1 <- A[2:4,]
x1
dim(x1)
```
$\newline$
```{R, echo=TRUE, comment=''}
x2 <- A[,1:3]
x2
dim(x2)
```
$\newline$
```{R, echo=TRUE, comment=''}
# Using a vector for EACH dimension
A[c(1,3),c(2,4)]
```
$\newline$
```{R, echo=TRUE, comment=''}
# Using 1 vector => Linear index
A[c(1,3,8,10)]
```
$\newline$
```{R, echo=TRUE, comment=''}
A[c(TRUE,FALSE,TRUE,TRUE,FALSE,TRUE),c(2,3)]
```
$\newline$
```{R, echo=TRUE, comment=''}
A[c(TRUE,FALSE,TRUE,TRUE,FALSE,TRUE),]
```
$\newline$
```{R, echo=TRUE, comment=''}
# Use of a linear index
A[c(TRUE,FALSE,TRUE,TRUE,FALSE,TRUE)]
```
* Use of a $\textbf{matrix}$:
```{R, echo=TRUE, comment=''}
A
```
$\newline$
```{R, echo=TRUE, comment=''}
mysubset <- matrix(c( 2, 1,
3, 5,
4, 2,
6, 5), ncol=2, byrow=TRUE )
A[mysubset]
```
### Exercises
* Create the following matrix A, given by:
```{R, echo=FALSE,comment=''}
NUM <-6
r1 <- 3^(1:NUM)
r2 <- 5^(1:NUM)
r3 <- 7^(1:NUM)
r4 <- 11^(1:NUM)
r5 <- 13^(1:NUM)
r6 <- 17^(1:NUM)
A <- rbind(r1,r2,r3,r4,r5,r6)
rownames(A) <- NULL
A
```
\begin{enumerate}
\item get element $343$
\item get the elements $25$, $625$, $2197$ and $4826809$ (all at once).
\item get the fourth row as a vector.
\item get the fourth row as a matrix.
\item get columns $2$ and $3$ (at the same time).
\item get everything except rows $2$ and $4$.
\item the diagonal of matrix A.
\end{enumerate}
## Operations on matrices
* Operations like $\textcolor{blue}{\textbf{*,/, +}}$ happpen element-wise.
* There are also more specialized functions:
* the mean over rows and columns ($\textcolor{blue}{\textbf{rowMeans()}}$, $\textcolor{blue}{\textbf{colMeans()}})$
* linear algebra functions ($\textcolor{blue}{\textbf{\%*\%}}$, $\textcolor{blue}{\textbf{t()}}$, ...)
### Examples
* Operations (by $\textbf{default: element-by-element}$):
```{R, echo=TRUE, comment=''}
A <- matrix(1:10, nrow=2)
B <- matrix( seq(10, 100, by=10), nrow=2)
A
B
```
$\newline$
```{R, echo=TRUE, comment=''}
A*B
```
$\newline$
```{R, echo=TRUE, comment=''}
C <- matrix(rep(2,10), nrow=2)
C
C**A
```
* Calculate $\textbf{row and column means}$ :
```{R, echo=TRUE, comment=''}
# Means of rows and columns
A
rowMeans(A)
colMeans(A)
```
* $\textbf{Matrix multiplication}$ ($\textcolor{blue}{\textbf{\%*\%}}$) :
```{R, echo=TRUE, comment=''}
A <- matrix(1:6, nrow=2)
A
B <- matrix(seq(10,120,by=10), nrow=3)
B
C <- A%*%B
C
dim(C)
```
* $\textbf{Linear algebra}$ routines
Some of the more common ones in R:
\begin{itemize}
\item $\textcolor{blue}{\textbf{solve()}}$ : $\textbf{invert}$ a square matrix
\item $\textcolor{blue}{\textbf{diag()}}$
\begin{itemize}
\item $\textbf{extracts}$ the diagonal of a matrix when a matrix is provided.
\item $\textbf{creates}$ a diagonal matrix when a vector is provided.
\end{itemize}
\item $\textcolor{blue}{\textbf{eigen()}}$ : calculates the $\textbf{eigenvalues}$ and $\textbf{eigenvectors}$ of a matrix
\item $\textcolor{blue}{\textbf{det()}}$ : calculates the $\textbf{determinant}$ of a matrix.
\item $\textcolor{blue}{\textbf{t()}}$: calculates the $\textbf{transpose}$$\footnote{Can also be used for dataframes (see later)}$ of a matrix.
\end{itemize}
```{R, echo=TRUE, comment=''}
# Invert matrix A
A <- matrix(c(1, 3, 2, 4), ncol = 2, byrow = T)
Ainv <- solve(A)
Ainv %*% A
```
$\newline$
```{R, echo=TRUE, comment=''}
# Create a diagonal matrix
C <- diag(c(1,4,7))
C
# Extract the diagonal elements
D <- matrix(1:8,nrow=4)
D
diag(D)
```
$\newline$
```{R, echo=TRUE, comment=''}
# Calculate eigenvalues and eigenvectors of A
r <- eigen(A)
r
# Eigenvalues
r$values
# Matrix with eigenvectors
r$vectors
# Diagonal Matrix (Similarity Transformation)
solve(r$vectors) %*% A %*% r$vectors
```
Note that under the hood $\texttt{R}$ calls [$\texttt{BLAS}$](https://netlib.org/blas/) and [$\texttt{LAPACK}$](https://netlib.org/lapack/).
```{R, echo=TRUE, comment=''}
# Find the version used of BLAS and LAPACK
La_library()
extSoftVersion()["BLAS"]
```
### Exercises
* Linear regression: $\newline$
- $\textbf{Step 1}$: $\newline$
Create a $\textbf{synthetic}$ data set by executing the following $\texttt{R}$ code:
```{R, echo=TRUE, results='hidden', comment=''}
x <- seq(from=0, to=20.0, by=0.25)
a <- 2.0
b <- 1.5
c <- 0.5
y <- a + b*x + c*x^2 + rnorm(length(x))
```
- $\textbf{Step 2}$: $\newline$
Our goal is to use the following linear model, i.e.:
\begin{eqnarray}
Y_i & = & \beta_0 \,+\, \beta_1 \, x_i \, + \, \beta_2\,x^2_i + \, \epsilon_i \nonumber \\
& = & \beta_0 \,+\, x_{i1} \,\beta_1 \,+ \, x_{i2}\,\beta_2 \, +\, \epsilon_i \nonumber
\end{eqnarray}
where $x_{ij}:= x^j_i$.
The aforementioned equation takes on the following matrix form:
\begin{equation}
Y = X\,\beta \, + \, \mathcal{\epsilon} \label{Eq:LinearModel}
\end{equation}
In Eq.(\ref{Eq:LinearModel}), we have:
\begin{itemize}
\item $Y$ : a $n \times 1$ column vector.
\item $X$ : a $n \times 3$ matrix (also known as the $\texttt{design matrix}$)
\item $\beta$: a $3 \times 1$ column vector.
\item $\epsilon$ is : a $n\times 1$ column vector and $\sim \, N(0,\sigma^2)$
\end{itemize}
An estimate for $\beta$ ($\widehat{\beta}$) can be found (using Least-Squares, MLE see e.g. [@SEBER:LR:2012a]) $\newline$
and has the following form:
\begin{equation}
\widehat{\beta} = (X^T X)^{-1} X^T Y \label{Eq:EstimateBeta}
\end{equation}
where,$\newline$
the column vector $Y$ is given by:
\begin{equation}
Y := \begin{bmatrix} y_1 \\ y_2 \\ .. \\ y_n \end{bmatrix} \nonumber
\end{equation}
and the matrix X\footnote{This is a known as a \href{https://en.wikipedia.org/wiki/Vandermonde_matrix}{Vandermonde} matrix.} takes the following form:
\begin{equation}
X := \begin{bmatrix} 1 & x_1 & x^2_1 \\
1 & x_2 & x^2_2 \\
\vdots & \vdots & \vdots \\
1 & x_n & x^2_n
\end{bmatrix} \nonumber
\end{equation}
*Note (additional background)*:\newline
1. The underlying assumption for Eq. (\ref{Eq:EstimateBeta}) is that the inverse of
the matrix $(X^T X)$ exists. This is the case
iff the $\texttt{rank}(X^T X)=\texttt{rank}(X)$ is maximal
or if the the columns of the matrix $X$ are linearly independent.\newline
2. In the field of machine learning (ML), the vector $\beta$ is split into 2 parts:
the scalar $\texttt{b}:=\beta_0$ ($\texttt{bias}$) and the
remainder of the vector $\beta$, i.e. ($\texttt{w}$) also
known as the $\texttt{weight}$ vector.\newline
In the current exercise, the column vector $\texttt{w}$ is given by
$\begin{pmatrix} \beta_1 \beta_2 \end{pmatrix}^T$.
$\textbf{Calculate}$ $\widehat{\beta}$ using Eq.(\ref{Eq:EstimateBeta}).\newline
An estimate for the residuals ($\widehat{\epsilon}$) is given by:
\begin{equation}
\widehat{\epsilon} = Y \,-\, X\,\widehat{\beta} \label{Eq:EstimateResiduals}
\end{equation}
$\textbf{Calculate}$ $\widehat{\epsilon}$ using Eq.(\ref{Eq:EstimateResiduals}).
- $\textbf{Step 3}$: $\newline$
You can check your results using the following $\texttt{R}$ code.
```{R,echo=TRUE,results='hide',comment=''}
myquadfit <- lm(y ~ x + I(x^2))
cat(sprintf("The estimates for beta::\n"))
cat(myquadfit$coefficients)
cat(sprintf("The residuals::\n"))
cat(myquadfit$residuals)
```
## Hash tables/dictionaries
We can also use hashes for matrices. We can select one or both dimensions.
To create hashes, for:
- rows: use $\textcolor{blue}{\textbf{rownames}}$
- columns: use $\textcolor{blue}{\textbf{colnames}}$
To remove the hash, use the $\textcolor{blue}{\textbf{NULL}}$ (like for vectors).
### Examples
```{R, echo=TRUE, comment=''}
A1 <- c(0 , 5471.52, 5091.57, 5392.82,
5416.45, 4584.33, 4904.83, 3851.73)
A2 <- c(5471.52, 0, 1315.28, 927.35,
1505.11, 944.40, 1157.42, 1945.42)
A3 <- c(5091.57, 1315.28, 0, 2166.00,
2724.01, 1571.76, 293.52, 1240.77)
A4 <- c(5392.82, 927.35, 2166.00, 0,
577.85, 973.23, 1947.28, 2422.32)
A5 <- c(5416.45, 1505.11, 2724.01, 577.85,
0, 1366.63, 2490.97, 2838.62)
A6 <- c(4584.33, 944.40, 1571.76, 973.23,
1366.63, 0, 1290.15, 1474.26)
A7 <- c(4904.83, 1157.42, 293.52, 1947.28,
2490.97, 1290.15, 0, 1064.41)
A8 <- c(3851.73, 1945.42, 1240.77, 2422.32,
2838.62, 1474.26, 1064.41, 0)
```
$\newline$
```{R, echo=TRUE, comment=''}
dist <- rbind(A1,A2,A3,A4,A5,A6,A7,A8)
dist
```
$\newline$
```{R, echo=TRUE, comment=''}
# Adding hashes to both rows and columns
cities <- c("Anchorage","Atlanta","Austin","Baltimore","Boston", "Chicago", "Dallas","Denver")
rownames(dist) <- cities
colnames(dist) <- cities
dist
```
$\newline$
```{R, echo=TRUE, comment=''}
dist["Chicago", "Denver"]
dist["Austin", "Boston"]
```
## Arrays
Say something about arrays.
\newpage
# Special Data Types (Factors and Date/Time types)
Every $\texttt{R}$ object has attributes (i.e. properties or metadata). $\newline$
They can be classified as:
* $\textbf{intrinisic}$ properties e.g. $\textcolor{blue}{\textbf{length()}}$
* $\textbf{external}$ properties (to be set by the user)
## Attributes
* can be get/retrieved using $\textcolor{blue}{\textbf{attributes()}}$.
* can be set:
- individually using $\textcolor{blue}{\textbf{attr()}}$
- in generally using $\textcolor{blue}{\textbf{structure()}}$
* some attributes can (also) be set/unset with $\textbf{special}$ functions:
- names: $\textcolor{blue}{\textbf{names()}}$
- dimension: $\textcolor{blue}{\textbf{dim()}}$
- comment : $\textcolor{blue}{\textbf{comment()}}$
- time series: $\textcolor{blue}{\textbf{tsp()}}$
- factor : $\textcolor{blue}{\textbf{factor()}}$ (see next section)
### Examples
* $1$ attribute:
```{R, echo=TRUE, comment=''}
x <- 1:5
x
attr(x, 'prop1') <- "hello"
attributes(x)
x
```
$\newline\newline$
```{R, echo=TRUE, comment=''}
attr(x, 'prop1') <- NULL
attributes(x)
x
```
$\newline\newline\newline$
* more than $1$ attribute:
```{R, echo=TRUE, comment=''}
y <- 1:8
y
y <- structure(y, dim=c(2,4), tag="trial")
y
attributes(y)
typeof(y)
class(y)
```
$\newline\newline$
```{R, echo=TRUE, comment=''}
# Remove BOTH attributes
y <- structure(y, dim=NULL, tag=NULL)
y
attributes(y)
typeof(y)
class(y)
```
$\newline\newline$
* $\textcolor{blue}{\textbf{names()}}$
```{R,echo=TRUE,comment=''}
# Set the names attribute
capitals <- c("Salt Lake City", "Carson City", "Boise", "Santa Fe")
names(capitals) <- c("UT", "NV", "ID", "NM")
capitals
attributes(capitals)
```
$\newline$
```{R,echo=TRUE,comment=''}
# Remove the names attribute
names(capitals) <- NULL
capitals
```
$\newline\newline$
* $\textcolor{blue}{\textbf{dim()}}$
```{R,echo=TRUE,comment=''}
x <- 1:12
x
typeof(x)
class(x)
```
$\newline\newline$
```{R,echo=TRUE,comment=''}
# Set the dimension attribute
dim(x) <- c(3,4)
x
typeof(x)
class(x)
```
$\newline\newline$
```{R,echo=TRUE,comment=''}
# Remove the dimension attribute
dim(x) <- NULL
x
typeof(x)
class(x)
```
* $\textcolor{blue}{\textbf{comment()}}$
```{R,echo=TRUE,comment=''}
x <- structure(1:6, comment="My vector")
typeof(x)
class(x)
comment(x)
```
## Factor variables (Categorical variables)
* Factor variables (factors, categorical variables) are
discrete variables (i.e not continuous). $\newline$
The factors bear labels ($\textbf{levels}$) which are
mapped into $\textbf{integers}$.
* Therefore, factors are stored as integer vector with $2$ attributes:
- $\textcolor{blue}{\textbf{class}}$= "factor"
- $\textcolor{blue}{\textbf{levels}}$: a vector with the "labels".
* By default ($\textbf{unordered}$) the labels are mapped $\textbf{alphabetically}$ to the integers.
We can $\textbf{impose}$ our own $\textbf{ordering}$ between integers and labels (levels).
* Useful functions:
- $\textcolor{blue}{\textbf{levels()}}$ : provides the levels of a factor
- $\textcolor{blue}{\textbf{table()}}$: returns the counts of each level
- $\textcolor{blue}{\textbf{is.factor()}}$: tests whether a variable is a factor variable
- $\textcolor{blue}{\textbf{is.ordered()}}$: tests whether a variable is an ordered factor variable
### Examples
* Creation of an $\textbf{unordered}$ factor
```{R,echo=TRUE,comment=''}
# Creation of an unordered factor
temp.data <- c("High","Low","VeryHigh","Low","VeryLow","Medium",
"VeryHigh","VeryHigh","Low","Low","Medium","VeryHigh",
"VeryHigh","VeryHigh","Low","High","VeryLow")
myfac.temp.data <- factor(temp.data)
myfac.temp.data
```
$\newline\newline$
```{R,echo=TRUE,comment=''}
# by default: the levels are stored ALPHABETICALLY (i.e. unordered)
levels(myfac.temp.data)
table(myfac.temp.data)
```
$\newline$
```{R,echo=TRUE,comment=''}
is.factor(myfac.temp.data)
is.ordered(myfac.temp.data)
```
$\newline$
* Creation of an $\textbf{ordered}$ factor
```{R,echo=TRUE,comment=''}
# Creation of an unordered factor
temp.data <- c("High","Low","VeryHigh","Low","VeryLow","Medium",
"VeryHigh","VeryHigh","Low","Low","Medium","VeryHigh",
"VeryHigh","VeryHigh","Low","High","VeryLow")
myfac2.temp.data <- factor(temp.data, ordered=TRUE,
levels=c("VeryLow","Low","Medium","High","VeryHigh"))
myfac2.temp.data
```
$\newline\newline$
```{R,echo=TRUE,comment=''}
# The ordering is NOW imposed
levels(myfac2.temp.data)
table(myfac2.temp.data)
```
$\newline\newline$
```{R,echo=TRUE,comment=''}
is.factor(myfac2.temp.data)
is.ordered(myfac2.temp.data)
```
$\newline\newline$
```{R,echo=TRUE,comment=''}
# Stripping a factor to the essentials: integer vector
attributes(myfac2.temp.data)
class(myfac2.temp.data) <- NULL
levels(myfac2.temp.data) <- NULL
myfac2.temp.data
```
## Dates and times in $\texttt{R}$.
* $\textcolor{blue}{\textbf{Date}}$ class :
- represents calendar dates
- built on top of doubles with class attribute 'Date'
- 0 : Jan 1. 1970 ($\href{https://en.wikipedia.org/wiki/Unix_time}{\textbf{Unix Epoch time}}$)
- $\textcolor{blue}{\textbf{as.Date()}}$: method to cast string to a Date
* $\textcolor{blue}{\textbf{POSIXct}}$ and $\textcolor{blue}{\textbf{POSIXlt}}$ : date and time
- $\textcolor{blue}{\textbf{POSIXct}}$: stores date/time values as the #seconds since Jan. 1, 1970
- $\textcolor{blue}{\textbf{POSIXlt}}$: stored as $\textbf{blue}{\textbf{list}}$ with elements
for seconds, minutes, hours, day, month, year, etc.
* $\href{https://lubridate.tidyverse.org/}{\textbf{lubridate}}$: a very useful package for dates and times: $\newline$
### Examples
* $\textbf{Date}$
```{R,echo=TRUE,comment=''}
today <- Sys.Date()
today
```
$\newline$
```{R,echo=TRUE,comment=''}
# Attributes of Date
class(today)
attributes(today)
```
$\newline$
```{R,echo=TRUE,comment=''}
unclass(today)
```
$\newline \newline$
```{R,echo=TRUE,comment=''}
d0 <- structure(0, class='Date')
d0
```
$\newline$
```{R,echo=TRUE,comment=''}
class(d0)
typeof(d0)
```
$\newline\newline$
```{R,echo=TRUE,comment=''}
# Convert a string into a Date
d1 <- as.Date("2022-01-01")
d1
```
$\newline$
```{R,echo=TRUE,comment=''}
class(d1)
typeof(d1)
```
$\newline \newline$
* $\textbf{POSIXct}$
```{R,echo=TRUE,comment=''}
# Convert a string into a POSIXct object
now_ct <- as.POSIXct("2018-08-01 22:00", tzone="MST")
now_ct
```
$\newline$
```{R,echo=TRUE,comment=''}
attributes(now_ct)
typeof(now_ct)
```
$\newline$
```{R,echo=TRUE,comment=''}
# Removal of the attributes
attr(now_ct,"tzone") <- NULL
unclass(now_ct)
```
# Bibliography