Extracting values from matrix by Column names

A row subset matrix can be extracted from the original matrix using a filter for the selected row names. Since a matrix’s elements are accessed in a dual index format, particular row selection can be carried out.

Syntax:

matrix[ vec , ] 

Where, vec contains the row names to be fetched

All the columns are retrieved from the data frame. The order of the rows and columns remains unmodified. The rows and column names remain unchanged after extraction. The result returned is a subset of the original matrix. The row names should be a proper subset of the original row names pertaining to matrix. 

Example:

R




# declaring matrix 
mat <- matrix(letters[1:12], ncol = 3)
  
# naming columns
colnames(mat) <- c("C1","C2","C3")
  
# naming rows
rownames(mat) <- c("R1","R2","R3","R4")
print ("Original Matrix")
print (mat)
  
# extracting rows 
row_vec <- c("R2","R4")
row_mat <- mat[row_vec ,]
  
print ("Modified Matrix")
print (row_mat)


Output

[1] "Original Matrix"
  C1  C2  C3
R1 "a" "e" "i"
R2 "b" "f" "j"
R3 "c" "g" "k"
R4 "d" "h" "l"
[1] "Modified Matrix"
  C1  C2  C3
R2 "b" "f" "j"
R4 "d" "h" "l"

Extract Values from Matrix by Column and Row Names in R

In this article, we will discuss how to extract values from the matrix by column and row names in R Programming Language.

Similar Reads

Extracting values from matrix by Column names

A row subset matrix can be extracted from the original matrix using a filter for the selected row names. Since a matrix’s elements are accessed in a dual index format, particular row selection can be carried out....

Extracting values from matrix by row names

...

Extracting values using both column and row names

A column subset matrix can be extracted from the original matrix using a filter for the selected column names. Since a matrix’s elements are accessed in a dual index format, particular row selection can be carried out....

Contact Us