Peter Nilsson
Peter Nilsson

Reputation: 3

R: Subset rows of matrix that do NOT match string vector

I have a matrix of gene expression data, where rows are different genes, and columns are samples.

I have a vector of genes that I want to filter out from the matrix. Creating a matrix with just those genes is easy with the basic syntax:

expression_matrix[excluded_genes,]

But I have no clue how to do the opposite, i.e. remove those genes from the matrix, instead of selecting them. I have searched around but not found (or understood) something that answers this problem.

Upvotes: 0

Views: 252

Answers (1)

kangaroo_cliff
kangaroo_cliff

Reputation: 6222

Hope this helps.

# Create data
X <- iris[1:4, ]

X
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1          5.1         3.5          1.4         0.2  setosa
#2          4.9         3.0          1.4         0.2  setosa
#3          4.7         3.2          1.3         0.2  setosa
#4          4.6         3.1          1.5         0.2  setosa

# Remove the rows one and two
rows_to_remove <- c("1", "2")
X[!rownames(X) %in% rows_to_remove, ]
#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#3          4.7         3.2          1.3         0.2  setosa
#4          4.6         3.1          1.5         0.2  setosa

Upvotes: 1

Related Questions