Page 31 - Applied Statistics with R
P. 31

3.2. DATA STRUCTURES                                               31


                      all(x + y == rep(x, 10) + y)


                      ## [1] TRUE


                      identical(x + y, rep(x, 10) + y)


                      ## [1] TRUE

                      # ?any
                      # ?all.equal



                      3.2.5   Matrices

                      R can also be used for matrix calculations. Matrices have rows and columns
                      containing a single data type. In a matrix, the order of rows and columns is
                      important. (This is not true of data frames, which we will see later.)
                      Matrices can be created using the matrix function.

                      x = 1:9
                      x


                      ## [1] 1 2 3 4 5 6 7 8 9


                      X = matrix(x, nrow = 3, ncol = 3)
                      X


                      ##       [,1] [,2] [,3]
                      ## [1,]     1    4    7
                      ## [2,]     2    5    8
                      ## [3,]     3    6    9

                      Note here that we are using two different variables: lower case x, which stores a
                      vector and capital X, which stores a matrix. (Following the usual mathematical
                      convention.) We can do this because R is case sensitive.

                      By default the matrix function reorders a vector into columns, but we can also
                      tell R to use rows instead.

                      Y = matrix(x, nrow = 3, ncol = 3, byrow = TRUE)
                      Y
   26   27   28   29   30   31   32   33   34   35   36