Extract Matrix Values by Row & Column Names in R (3 Examples)

In this tutorial, I’ll illustrate how to get certain column and row values using column and row names of a matrix in the R programming language.

Introducing Example Data

mat <- matrix(1:20, ncol = 4)        # Constructing matrix in R
rownames(mat) <- paste0("r", 1:5)    # Setting up row names
colnames(mat) <- paste0("c", 1:4)    # Setting up column names
mat                                  # Showing example matrix in RStudio console
#    c1 c2 c3 c4
# r1  1  6 11 16
# r2  2  7 12 17
# r3  3  8 13 18
# r4  4  9 14 19
# r5  5 10 15 20

Example 1: Using Row Names to Extract Particular Rows from Matrix

mat[c("r1", "r4"), ]                 # Selecting certain rows
#    c1 c2 c3 c4
# r1  1  6 11 16
# r4  4  9 14 19

Example 2: Using Column Names to Extract Particular Variables from Matrix

mat[ , c("c2", "c3")]                # Selecting certain columns
#    c2 c3
# r1  6 11
# r2  7 12
# r3  8 13
# r4  9 14
# r5 10 15

Example 3: Using Row & Column Names to Extract Particular Rows & Columns from Matrix

mat[c("r2", "r4", "r5"),             # Selecting certain rows & columns
    c("c3", "c4")]
#   c2 c3
# r1  6 11
# r2  7 12
# r3  8 13
# r4  9 14
# r5 10 15

Further Resources & Related Articles

Here, you may find some additional resources on topics such as data inspection, indices, and extracting data.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top