Page 230 - Data Science class 11
P. 230

Thus, matrices are an extension of numeric or character vectors. In other words, they are atomic vectors arranged in
        a two-dimensional rectangular layout. As a matrix is an atomic vector extension, its elements must be of the same
        data type.
        To create a matrix in R, we use the matrix() function.


        6.9.1 the syntax for creating a matrix in r is:

                 matrix(data, nrow, ncol, byrow, dimname)
        The parameters used in matrices are as follows:
           • data: the input vector which becomes the data elements of the matrix.

           • nrow: number of rows to be created.
           • ncol: number of columns to be created.
           • byrow: represents a logical clue. When it is set to TRUE, then the elements in the input vector are organised by row.
           • dimname: is the names assigned to the rows and columns.

             #Example of a matrix with no data source
        Example

        Enter the following code snippet:

             y <- matrix(nrow = 2, ncol = 2)
             y
        Results obtained when the code above is run:

















        NA means data not available.

        6.9.2 creating a matrix taking a vector of numbers as input.

        Example
        Enter the following code snippet:

             # Elements will be shown arranged sequentially by row.
             u <- matrix(c(3:14), nrow = 4, byrow = TRUE)
             print(u)
             # Elements will be shown arranged sequentially by column.
             v <- matrix(c(3:14), nrow = 4, byrow = FALSE)
             print(v)
             # Define the column and row names.
             rownames = c("row1", "row2", "row3", "row4")
             colnames = c("column1", "colum2", "column3")




          228   Touchpad Data Science-XI
   225   226   227   228   229   230   231   232   233   234   235