Delete the list of growth names from the matrix in R

I have a matrix of entries:

testMat <- matrix(1:30, nrow = 10)
rownames(testMat) <- letters[1:10]

... and a list of growth names:

rem <- c("d", "e", "f", "i")

Retrieving a matrix containing only rows with names contained in the rem list is easy:

testMat[rem,]

Following this logic, I would like to remove the rows with the names indicated in the "rem" list from the matrix. But

testMat[-rem,]

not working with Error in -rem : invalid argument to unary operator. Why is this not working?

+3
source share
3 answers

You are looking for %in%:

testMat[!rownames(testMat) %in% rem, ]

  [,1] [,2] [,3]
a    1   11   21
b    2   12   22
c    3   13   23
g    7   17   27
h    8   18   28
j   10   20   30

Negative indexing only works for numeric indices.

+2
source

This is a little longer, but you can do it:

testMat[which(! rownames(testMat) %in% rem),]

  [,1] [,2] [,3]
a    1   11   21
b    2   12   22
c    3   13   23
g    7   17   27
h    8   18   28
j   10   20   30
+2
source

To add to the parameters, I usually like setdifffor things like this:

setdiff(rownames(testMat), rem)
# [1] "a" "b" "c" "g" "h" "j"
testMat[setdiff(rownames(testMat), rem), ]
#   [,1] [,2] [,3]
# a    1   11   21
# b    2   12   22
# c    3   13   23
# g    7   17   27
# h    8   18   28
# j   10   20   30
+1
source

All Articles