Reputation: 776
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
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
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
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