Page 38 - Applied Statistics with R
P. 38
38 CHAPTER 3. DATA AND PROGRAMMING
Calculations with Vectors and Matrices
Certain operations in R, for example %*% have different behavior on vectors and
matrices. To illustrate this, we will first create two vectors.
a_vec = c(1, 2, 3)
b_vec = c(2, 2, 2)
Note that these are indeed vectors. They are not matrices.
c(is.vector(a_vec), is.vector(b_vec))
## [1] TRUE TRUE
c(is.matrix(a_vec), is.matrix(b_vec))
## [1] FALSE FALSE
When this is the case, the %*% operator is used to calculate the dot product,
also know as the inner product of the two vectors.
The dot product of vectors = [ , , ⋯ ] and = [ , , ⋯ ] is defined to
2
1
1
2
be
⋅ = ∑ = + + ⋯ .
1 1
2 2
=1
a_vec %*% b_vec # inner product
## [,1]
## [1,] 12
a_vec %o% b_vec # outer product
## [,1] [,2] [,3]
## [1,] 2 2 2
## [2,] 4 4 4
## [3,] 6 6 6
The %o% operator is used to calculate the outer product of the two vectors.
When vectors are coerced to become matrices, they are column vectors. So a
vector of length becomes an × 1 matrix after coercion.

