Page 231 - Data Science class 11
P. 231

P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
                print(P)
            On execution of the above code, the following result is shown:
































            6.9.3 accessing elements of a matrix

            Elements of a matrix can be accessed by using the column and row indexes of the element. We consider the matrix P
            above to find the specific elements below.

            The code snippet given below illustrates how you can access different elements in an array.
            Example

            Enter the following code snippet:

                P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
                print(P)
                # Define the column and row names.
                rownames = c("row1", "row2", "row3", "row4")

                colnames = c("col1", "col2", "col3")
                # Create the matrix.
                P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
                # Access the element at 3rd column and 1st row.
                print(P[1,3])
                # Access the element at 2nd column and 4th row.
                print(P[4,2])

                # Access only the  2nd row.
                print(P[2,])
                # Access only the 3rd column.
                print(P[,3])




                                                                                         Programming with R    229
   226   227   228   229   230   231   232   233   234   235   236