R – Get Specific Row of Matrix
To get a specific row of a matrix, specify the row number followed by a comma, in square brackets, after the matrix variable name. This expression returns the required row as a vector.
In this tutorial, we will learn how to get a single row from a Matrix, with examples.
The syntax of the expression to get a row at given number/position/index in a matrix is
The expression returns the row as a vector from matrix
X at given
In the following program, we create a matrix and get the row at position
data <- c(2, 4, 7, 5, 10, 8) A <- matrix(data, nrow = 2) row <- A[2, ] print("Matrix A") print(A) print("Row") print(row)
 "Matrix A" [,1] [,2] [,3] [1,] 2 7 10 [2,] 4 5 8  "Row"  4 5 8
If the row number is out of bounds for given matrix, then R throws Error “subscript out of bounds”.
Let us try to get a row at
row = 5, where the matrix has only
data <- c(2, 4, 7, 5, 10, 8) A <- matrix(data, nrow = 2) row <- A[5, ]
Error in A[5, ] : subscript out of bounds
In this R Tutorial, we learned how to get specific row of a Matrix at given row position in R, with the help of examples.