R – Get Specific Column of Matrix

To get a specific column of a matrix, specify the column number preceded 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 column from a Matrix, with examples.

Syntax

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

X[, column]

where

ArgumentDescription
XA matrix.
columnColumn number.

Return Value

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

ADVERTISEMENT

Examples

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

example.R

data <- c(2, 4, 7, 5, 10, 8)
A <- matrix(data, nrow = 2)
column <- A[, 2]

print("Matrix A")
print(A)
print("Column")
print(column)

Output

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

If the column number is out of bounds for given matrix, then R throws Error “subscript out of bounds”.

Let us try to get a row at column = 5, where the matrix has only 3 rows.

example.R

data <- c(2, 4, 7, 5, 10, 8)
A <- matrix(data, nrow = 2)
column <- A[, 5]

Output

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

Conclusion

In this R Tutorial, we learned how to get specific column of a Matrix at given column position in R, with the help of examples.