To access matrix elements using indexing and slicing in R, you can use square brackets []
with row and column indices. R uses 1-based indexing, so the first element is at position [1,1]. You can also use slicing to access submatrices by specifying ranges of rows and columns.
In this example,
matrix
with values from 1 to 9 arranged in 3 rows and 3 columns using the matrix()
function.matrix()
function takes a vector of values and the arguments nrow
and ncol
to specify the number of rows and columns respectively.matrix[2, 3]
accesses the element in the 2nd row and 3rd column of matrix
.element
and print it to standard output.matrix <- matrix(1:9, nrow = 3, ncol = 3)
element <- matrix[2, 3]
print(element)
[1] 6
In this example,
matrix
with values from 1 to 12 arranged in 3 rows and 4 columns using the matrix()
function.matrix()
function takes a vector of values and the arguments nrow
and ncol
to specify the number of rows and columns respectively.matrix[1, ]
accesses all the elements in the 1st row of matrix
.row
and print it to standard output.matrix <- matrix(1:12, nrow = 3, ncol = 4)
row <- matrix[1, ]
print(row)
[1] 1 4 7 10
In this example,
matrix
with values from 1 to 16 arranged in 4 rows and 4 columns using the matrix()
function.matrix()
function takes a vector of values and the arguments nrow
and ncol
to specify the number of rows and columns respectively.matrix[2:4, 2:4]
accesses the elements in rows 2 to 4 and columns 2 to 4 of matrix
.submatrix
and print it to standard output.matrix <- matrix(1:16, nrow = 4, ncol = 4)
submatrix <- matrix[2:4, 2:4]
print(submatrix)
[,1] [,2] [,3] [1,] 6 10 14 [2,] 7 11 15 [3,] 8 12 16
In this tutorial, we learned How to Access Matrix Elements using Indexing and Slicing in R language with well detailed examples.