-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathR-Studio Notebook Vectors Matrices.Rmd
137 lines (105 loc) · 2.06 KB
/
R-Studio Notebook Vectors Matrices.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
---
title: "R Notebook: Lesson 4, Vectors and Matrices"
output: html_notebook
---
Creating and Modifying Vectors
```{r}
V <- c(1,2,3,4,5,6)
print(V[1:3])
print(V[5])
V2 <- V[3:5]
print(V2)
V3 <- 1:9
V3[10] <- 10
print(V3)
```
Basic Vector Operations
```{r}
print(V+1)
print(V*2)
print(V[1:3] / V2)
crossprod(V[1:3], V2)
```
Creating and Modifying Matrices
```{r}
A <- matrix(1:9, nrow = 3, byrow = TRUE)
B <- matrix(1:2, ncol = 2)
I <- diag(3)
print("MATRIX A")
print(A)
print("MATRIX B")
print(B)
print("Identity Matrix I")
print(I)
colnames(A) <- c("price", "store no.", "inventory")
rownames(A) <- c("item1", "item2", "item3")
print(A)
print(A[1:2,])
print(A[,2:3])
```
Linear Algebra Examples
```{r}
#Multiplying by the Identity Matrix
print(A*I)
#Matrix Multiplication of a matrix mxn by a matrix nxp (or, in this case, nxn)
E <- matrix(2:7, nrow = 2)
F <- matrix(2:7, ncol = 2)
print(E%*%F)
# Matrix Muliplied by a Vector
g <- c(7,17)
print(F%*%g)
# Identity
solve(E%*%F)
# Determinant
det(E%*%F)
# Row
row(A)
# Col
col(A)
# Boolean matrix, produced by comparison
row(A)==col(A)
# Diag
diag(A)
```
Generating a Covariance Matrix
Example from the book "The Art of Programming in R" by Norman Matloff (2011)
```{r}
makecov <- function(rho,n) {
m <- matrix(nrow=n,ncol=n)
m <- ifelse(row(m) == col(m),1,rho)
return(m)
}
Z <- matrix(3:8, ncol = 2)
print(Z)
X <- makecov(0.2, 5)
print(X)
print(X[,1:2]%*%t(Z))
```
Using the apply function on a matrix
Example from the book "The Art of Programming in R" by Norman Matloff (2011)
```{r}
print(Z)
apply(Z,2,mean)
f <- function(x) x/c(2,8)
Y <- apply(Z,1,f)
print(Y)
```
Beware of Unintended Dimension Reduction!
```{r}
M <- matrix(1:8, ncol = 2)
print(M)
r <- M[2,]
# R is a vector, not a 1 dimensional matrix!
print(r)
print("Attributes of M: ")
print(attributes(M))
print("Attributes of r: ")
print(attributes(r))
# There are none, because r is a vector.
# Is this what we expected?
print(M%*%r)
# Using the 'drop' argument to maintain the slice as a 1x2 matrix
m <- M[2,, drop=FALSE]
print(attributes(m))
print(M%*%t(m))
```