-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4_Operations.Rmd
More file actions
52 lines (44 loc) · 1.42 KB
/
4_Operations.Rmd
File metadata and controls
52 lines (44 loc) · 1.42 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
---
title: "Matrix operations in R"
author: "Dhiraj Saharia"
date: "08/02/2020"
output:
html_document:
df_print: paged
theme: flatly
toc: yes
number_sections: true
---
* Matrix operations -
1. Rectangular arrangement of numbers in rows and columns.
2. Rows - horizontally and Columns - Vertically
```{r}
A = matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, ncol = 3, byrow = TRUE)
print(A)
```
* Special Matrices -
* Scalar Matrix - All rows and columns are filled with constant `k`. `matrix(k, m, n)`.
* Diagonal Matrix - Diagonals are filled with k or a vector. `diag(c(1,2,3), 3, 3)`.
* Identity Matrix - Diagonals are 1. Use `diag(1, m, n)`.
* Matrix metrics -
* `dim(A)` - return size of matrix.
* `nrow(A)` - return number of rows.
* `ncol(A)` - return number of columns.
* `length(A)` - return number of elements.
* Accessing, editing and deleting in elements in matrices -
* Same notation used as dataframes.
* `rownames()` and `colnames()`.
```{r}
colnames(A) = c("a", "b", "c")
rownames(A) = c("e", "f", "g")
print(A)
```
* Accessing an entry in the matrix -
* `A[2,3]` - 2nd row and 3rd column.
* `A[,3]` - Third column only. and `A[2,]` - Row two only.
* `A[,-2]` - Everything except the second column.
* Colon Operator -
* Used to pick sub-matrices.
* `A[1:3, 1:2]` - Rows 1,2 and 3 with columns 1 and 2.
* `A[c(1,3), 1:2]` - Rows 1 and 3 with columns 1 and 2.
* Matrix Concatenation -