roschu
roschu

Reputation: 776

Remove a list of rownames from matrix in R

I have a matrix of entries:

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

... and a list of rownames:

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

Extracting a matrix containing only the rows with names provided in the list 'rem' is easy:

testMat[rem,]

Following this logic I would like to remove the rows with names provided in the list 'rem' from the matrix. But

testMat[-rem,]

failes with Error in -rem : invalid argument to unary operator. Why does that not work?

Upvotes: 3

Views: 365

Answers (3)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

To add to the options, I usually like setdiff for these kinds of things:

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

Upvotes: 1

Pop
Pop

Reputation: 12411

It is a bit long but you can do that :

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

Upvotes: 2

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

You're 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 works for numeric indices only.

Upvotes: 2

Related Questions