Get element at the specific position from matrix in R
Last Updated :
20 Dec, 2023
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
R
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
R
mat <- matrix (1:12,3,4)
mat
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
R
row_vector <- mat[2, ]
print (row_vector)
col_vector <- mat[, 3]
print (col_vector)
|
Output:
[1] 2 5 8 11
[1] 7 8 9
Accessing Subsetting Matrix
R
mat <- matrix (1:12,3,4)
subset_mat <- mat[1:2, 2:3]
print (subset_mat)
|
Output:
[,1] [,2]
[1,] 4 7
[2,] 5 8
Accessing matrix Conditional Access
R
mat <- matrix (1:12,3,4)
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...