How to access elements of Matrix in R?

Accessing matrix elements in R

Like C and C++, we can easily access the elements of our matrix by using the index of the element. There are three ways to access the elements from the matrix.

  1. We can access the element which presents on nth row and mth column.
  2. We can access all the elements of the matrix which are present on the nth row.
  3. We can also access all the elements of the matrix which are present on the mth column.

Let see an example to understand how elements are accessed from the matrix present on nth row mth column, nth row, or mth column.

Example

# Defining the column and row names.  
row_names = c("row1", "row2", "row3", "row4")  
ccol_names = c("col1", "col2", "col3")  
#Creating matrix   
R <- matrix(c(5:16), nrow = 4, byrow = TRUE, dimnames = list(row_names, col_names))  
print(R)  
  
#Accessing element present on 3rd row and 2nd column  
print(R[3,2])  
  
#Accessing element present in 3rd row  
print(R[3,])  
  
#Accessing element present in 2nd column  
print(R[,2])

Output

      col1 col2 col3
row1    5    6    7
row2    8    9   10
row3   11   12   13
row4   14   15   16

[1] 12

col1 col2 col3
  11   12   13

row1 row2 row3 row4
   6    9   12   15