How to Select a Row or Column from a Matrix in R

04.12.2021

Now that you know how to create matrices, it would be good to learn how to select out rows and columns to perform operations on. In this article, we will learn how to select a row or column from a matrix in R.

The first way we can select a row or column is using the [] brackets. We can pass a row and a column in these brackets separate by a comma. For example, [1,2] means the first row, second column.

However, if we leave one of these selectors blank, we can select all rows or all columns. For example if we type [1, ], this means select the first row and all the columns. Let's see some examples.

data.vec = c(100, 10, 2, 400, 20, 2, 400, 10, 2)

mat = matrix(data.vec, 3, 3, byrow=TRUE)
mat

# select the first row
row = mat[1, ]
row
# [1] 100  10   2

# select the second column
col = mat[, 2]
col
# [1] 10 20 10

You may have noticed that using the above returns a vector for the row and the column. If you would like to have R return a matrix instead, we can use the drop=FALSE option.

# select the first row
row = mat[1, , drop=FALSE]
row
#      [,1] [,2] [,3]
# [1,]  100   10    2

# select the second column
col = mat[, 2, drop=FALSE]
col
#       [,1]
# [1,]   10
# [2,]   20
# [3,]   10