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.

Syntax

The syntax of the expression to get a row at given number/position/index in a matrix is

</>
Copy
X[row, ]

where

ArgumentDescription
XA matrix.
rowRow number.

Return Value

The expression returns the row as a vector from matrix X at given row number.

Examples

In the following program, we create a matrix and get the row at position 2.

example.R

</>
Copy
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)

Output

[1] "Matrix A"
     [,1] [,2] [,3]
[1,]    2    7   10
[2,]    4    5    8
[1] "Row"
[1] 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 2 rows.

example.R

</>
Copy
data <- c(2, 4, 7, 5, 10, 8)
A <- matrix(data, nrow = 2)
row <- A[5, ]

Output

Error in A[5, ] : subscript out of bounds

Conclusion

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.