Linear Algebra Operations on Vectors and Matrices

Multiplying a vector by a scalar works directly, as you saw earlier. Here’s another example:

> y
[1]  1  3  4 10
> 2*y
[1]  2  6  8 20

If you wish to compute the inner product (or dot product) of two vectors, use crossprod(), like this:

> crossprod(1:3,c(5,12,13))
     [,1]
[1,]   68

The function computed 1 · 5 + 2 · 12 + 3 · 13 = 68.

Note that the name crossprod() is a misnomer, as the function does not compute the vector cross product. We’ll develop a function to compute real cross products in Section 8.4.1.

For matrix multiplication in the mathematical sense, the operator to use is %*%, not *. For instance, here we compute the matrix product:

Here’s the code:

> a [,1] [,2] [1,] 1 2 [2,] 3 4 > b [,1] [,2] [1,] ...

Get The Art of R Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.