R – Get Multiple Rows of Matrix

To get multiple rows of matrix, specify the row numbers as a vector followed by a comma, in square brackets, after the matrix variable name. This expression returns the required rows as a matrix.

In this tutorial, we will learn how to get a multiple rows from a Matrix, with examples.

Syntax

The syntax of the expression to get multiple rows at given vector of positions/indices in a matrix is

</>
Copy
X[rows, ]

where

ArgumentDescription
XA matrix.
rowsA vector of row numbers.

Return Value

The expression returns the selected rows as a matrix from matrix X at given rows numbers.

Examples

In the following program, we create a matrix and get the rows at position 1 and 3. We pass the vector c(1, 3) for the rows in the expression X[rows, ].

example.R

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

print("Matrix A")
print(A)
print("Selected Rows")
print(rows)

Output

[1] "Matrix A"
     [,1] [,2] [,3]
[1,]    2    5    1
[2,]    4   10    3
[3,]    7    8    5
[1] "Selected Rows"
     [,1] [,2] [,3]
[1,]    2    5    1
[2,]    7    8    5

If any of the row numbers is out of bounds for given matrix, then R throws Error “subscript out of bounds”.

Let us try to get a rows at rows = c(1, 2, 5), where the matrix has only 3 rows. Since row number 5 is out of bounds for the given matrix, R must throw the error.

example.R

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

Output

Error in A[c(1, 2, 5), ] : subscript out of bounds

Conclusion

In this R Tutorial, we learned how to get multiple rows of a Matrix at given row positions in R, with the help of examples.