delete a row and column from matrix by name in r

To delete a row or column from a matrix based on the row or column name in R, you can use the following approach:

  1. Delete a row based on row name:
# Create a sample matrix
mat <- matrix(1:9, nrow = 3, dimnames = list(c("A", "B", "C"), c("X", "Y", "Z")))
mat
# Delete row "B"
mat <- mat[-which(rownames(mat) == "B"), ]
mat
175 chars
7 lines
  1. Delete a column based on column name:
# Create a sample matrix
mat <- matrix(1:9, nrow = 3, dimnames = list(c("A", "B", "C"), c("X", "Y", "Z")))
mat
# Delete column "Y"
mat <- mat[, -which(colnames(mat) == "Y")]
mat
178 chars
7 lines

In the above code snippets, we are deleting a row with the name "B" and a column with the name "Y" from the sample matrix mat.

related categories

gistlibby LogSnag