从R中的矩阵中删除rownames列表

时间:2014-02-26 11:38:38

标签: r matrix

我有一个条目矩阵:

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

...和一个rownames列表:

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

提取仅包含列表'rem'中提供的名称的行的矩阵很容易:

testMat[rem,]

遵循这个逻辑,我想从矩阵中删除列表'rem'中提供名称的行。但

testMat[-rem,]

Error in -rem : invalid argument to unary operator一起失败。 为什么这不起作用?

3 个答案:

答案 0 :(得分:2)

您正在寻找%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

负数索引仅适用于数字索引。

答案 1 :(得分:2)

有点长但你可以这样做:

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 :(得分:1)

要添加选项,我通常会喜欢setdiff来处理这些事情:

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
相关问题