-
Notifications
You must be signed in to change notification settings - Fork 1
/
matrix.Rmd
89 lines (62 loc) · 1.72 KB
/
matrix.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
## Matrices
* A matrix is a **2 dimensional** vector.
* All columns in a matrix must have:
+ the same **type** (numeric, character or logical)
+ the same **length**
### Creating a matrix
* From vectors with the **rbind** function:
```{r}
x <- c(1, 44)
y <- c(0, 12)
z <- c(34, 4)
# rbind: bind rows
b <- rbind(x, y, z)
```
* From vectors with the **cbind** function:
```{r}
i <- c(1, 0, 34)
j <- c(44, 12, 4)
# cbind: bind columns
k <- cbind(i, j)
```
* From scratch with the *matrix* function:
```{r}
# nrow: number of rows
# ncol: number of columns
pp <- matrix(c(1, 0, 34, 44, 12, 4),
nrow=3,
ncol=2)
```
### Two-dimensional object
Vectors have one index per element (1-dimension).<br>
Matrices have **two indices (2-dimensions)** per element, corresponding to its corresponding location: row and column number:
<img src="images/matrix_indices.png" width="300"/>
* Fetching elements of a matrix:
The "coordinates" of an element in a 2-dimensional object will be first the row (on the left of the comma), then the column (on the right of the comma):
<img src="images/matrix_rc.png" alt="rstudio logo" width="250"/>
### Matrix manipulation
* Add 1 to all elements of a matrix
```{r}
b <- b + 1
```
* Multiply by 3 all elements of a matrix
```{r}
b <- b * 3
```
* Subtract 2 to each element of **the first row** of a matrix
```{r}
b[1, ] <- b[1, ] - 2
```
* Replace elements that comply a condition:
```{r}
# Replace all elements that are greater than 3 with NA
b[ b > 3 ] <- NA
```
**HANDS-ON**
1. Create a matrix, using the 2 following vectors **vv1** and **vv2** as columns:
```{r}
vv1 <- c(43, 21, 54, 65, 25, 44)
vv2 <- c(0, 1, 1, 0, 1, 0)
```
Save the matrix in the object **mm1**.
2. Add **2** to each element of **mm1**.