Extracting values using both column and row names
Similar to the above approaches, the rows, and columns can also be extracted, by specifying the chosen vectors for both indexes.
Syntax:
matrix[ rowvec , colvec ]
Where, rowvec contains the row names to be fetched and colvec the column names
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 ( "R1" , "R3" ) # extracting columns col_vec <- c ( "C1" , "C3" ) col_mat <- mat[row_vec ,col_vec] print ( "Modified Matrix" ) print (col_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 C3 R1 "a" "i" R3 "c" "k"
Any single element or cell value can also be fetched from the matrix, by simply specifying the row name and column name as the indexes for retrieval.
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 single element col_mat <- mat[ "R3" , "C2" ] print ( "Modified Matrix" ) print (col_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" [1] "k"
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.
Contact Us