Page 39 - Applied Statistics with R
P. 39

3.2. DATA STRUCTURES                                               39


                      as.matrix(a_vec)


                      ##       [,1]
                      ## [1,]     1
                      ## [2,]     2
                      ## [3,]     3

                      If we use the %*% operator on matrices, %*% again performs the expected matrix
                      multiplication. So you might expect the following to produce an error, because
                      the dimensions are incorrect.

                      as.matrix(a_vec) %*% b_vec


                      ##       [,1] [,2] [,3]
                      ## [1,]     2    2    2
                      ## [2,]     4    4    4
                      ## [3,]     6    6    6


                      At face value this is a 3 × 1 matrix, multiplied by a 3 × 1 matrix. However,
                      when b_vec is automatically coerced to be a matrix, R decided to make it a “row
                      vector”, a 1 × 3 matrix, so that the multiplication has conformable dimensions.
                      If we had coerced both, then R would produce an error.

                      as.matrix(a_vec) %*% as.matrix(b_vec)


                      Another way to calculate a dot product is with the crossprod() function. Given
                      two vectors, the crossprod() function calculates their dot product. The func-
                      tion has a rather misleading name.

                      crossprod(a_vec, b_vec)    # inner product



                      ##       [,1]
                      ## [1,]    12

                      tcrossprod(a_vec, b_vec)    # outer product


                      ##       [,1] [,2] [,3]
                      ## [1,]     2    2    2
                      ## [2,]     4    4    4
                      ## [3,]     6    6    6
   34   35   36   37   38   39   40   41   42   43   44