Open In App

Get element at the specific position from matrix in R

At any point in time, a matrix may be required to be traversed for an element at a specific position. In this article, we are going to access the elements from a matrix in R Programming Language using integer vector, and logical vector as the index.

Accessing Elements in a Matrix

In R Programming Language we have several methods to Accessing Elements in a Matrix In R we can access matrix elements using square brackets [ ] notation.



Create a matrix




# Create a matrix
mat <- matrix(1:12,3,4)
 
mat

Output:

     [,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12

Accessing Single Element in a Matrix




# Create a matrix
mat <- matrix(1:12,3,4)
mat
 
# Access the element in the 1st row and 2nd column
element <- mat[1, 2]
print(element)

Output:



     [,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12

[1] 4

Accessing Entire Row or Column




# Access the entire 2nd row
row_vector <- mat[2, ]
print(row_vector)
 
# Access the entire 3rd column
col_vector <- mat[, 3]
print(col_vector)

Output:

[1]  2  5  8 11

[1] 7 8 9

Accessing Subsetting Matrix




# Create a 3x4 matrix
mat <- matrix(1:12,3,4)
 
# Subset a 2x2 matrix from the original
subset_mat <- mat[1:2, 2:3]
print(subset_mat)

Output:

     [,1] [,2]
[1,] 4 7
[2,] 5 8

Accessing matrix Conditional Access




# Create a 3x4 matrix
mat <- matrix(1:12,3,4)
 
# Access elements greater than 5
greater_than_5 <- mat[mat > 5]
print(greater_than_5)

Output:

[1]  6  7  8  9 10 11 12

These methods provide flexibility depending on our specific needs and the structure of our matrices. Choose the one that best fits our use case.


Article Tags :