R – Get Multiple Columns of Matrix
To get multiple columns of matrix, specify the column numbers as a vector preceded by a comma, in square brackets, after the matrix variable name. This expression returns the required columns as a matrix.
In this tutorial, we will learn how to get a multiple columns from a Matrix, with examples.
Syntax
The syntax of the expression to get multiple columns at given vector of positions/indices in a matrix is
X[, columns]
where
Argument | Description |
---|---|
X | A matrix. |
columns | A vector of column numbers. |
Return Value
The expression returns the selected columns as a matrix from matrix X
at given columns
numbers.
Examples
In the following program, we create a matrix and get the columns at position 1
and 3
. We pass the vector c(1, 3)
for the columns
in the expression X[, columns]
.
example.R
data <- c(2, 4, 7, 5, 10, 8, 1, 3)
A <- matrix(data, nrow = 2)
columns <- A[, c(1, 3)]
print("Matrix A")
print(A)
print("Selected Columns")
print(columns)
Output
[1] "Matrix A"
[,1] [,2] [,3] [,4]
[1,] 2 7 10 1
[2,] 4 5 8 3
[1] "Selected Columns"
[,1] [,2]
[1,] 2 10
[2,] 4 8
If any of the column numbers is out of bounds for given matrix, then R throws Error “subscript out of bounds”.
Let us try to get a columns at columns = c(1, 2, 5)
, where the matrix has only 4
rows. Since column number 5
is out of bounds for the given matrix, R must throw the error.
example.R
data <- c(2, 4, 7, 5, 10, 8, 1, 3)
A <- matrix(data, nrow = 2)
columns <- 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 columns of a Matrix at given column positions in R, with the help of examples.