如何通过行名而不是数字索引来删除矩阵的行?

时间:2021-10-08 19:45:31

I'm sure this has a simple answer, having trouble finding it.

我相信这个答案很简单,很难找到答案。

So I have matrix g:

我有矩阵g

> g[1:5,1:5]
        rs7510853 rs10154488 rs12159982 rs2844887 rs2844888
NA06985 "CC"      "CC"       "CC"       "CC"      "CC"     
NA06991 "CC"      "CC"       "CC"       "CC"      "CC"     
NA06993 "CC"      "CC"       "CC"       "CC"      "CC"     
NA06994 "CC"      "CC"       "CC"       "CC"      "CC"     
NA07000 "CC"      "CC"       "CC"       "CC"      "CC"     
> rownames(g)[1:2]->remove
> remove
[1] "NA06985" "NA06991"
> g[-remove,]

Error in -remove : invalid argument to unary operator

Is there a simple way to do what I want to do here (remove the ID's referenced in the vector 'remove' from matrix g?

有没有一种简单的方法来做我想做的事情(从矩阵g中移除向量“remove”中引用的ID ?

Btw this is just a model for what I actually want to do, please don't say just do g[-(1:2),] , I need to be able to remove a whole bunch of rows that I have ID-d.

顺便说一下,这只是我想要做的一个模型,请不要说只做g[-(1:2),],我需要能够删除我有ID-d的所有行。

3 个解决方案

#1


51  

When working with indexing, you cannot use "negative" character vectors. You can convert to logical with %in%

在使用索引时,不能使用“负”字符向量。您可以将%转换为%的逻辑值

g[!rownames(g) %in% remove, ]

If you really wanted to use negative-indexing this could be done:

如果你真的想使用负索引,可以这样做:

g[-which(rownames(g) %in% remove), ]

... however it has a nasty potential erroneous result that arises when there are not any rownames in the target vector. The result may be no values returned.

…然而,当目标向量中没有任何行名时,就会出现令人讨厌的潜在错误结果。结果可能是没有返回值。

#2


7  

You cannot negative index a character vector when indexing. Turn your vector remove into a boolean. I've defined a function

索引字符向量时不能为负索引。将矢量移动到布尔值。我已经定义了一个函数

`%notin%` <- function(x,y) !(x %in% y) 

which can then be used as such: g[rownames(g) %notin% remove ,]

然后可以这样使用:g[rowname (g) %notin% remove,]

#3


3  

I use "setdiff" as follows:

我使用“setdiff”如下:

g[setdiff(rownames(g),remove),]

#1


51  

When working with indexing, you cannot use "negative" character vectors. You can convert to logical with %in%

在使用索引时,不能使用“负”字符向量。您可以将%转换为%的逻辑值

g[!rownames(g) %in% remove, ]

If you really wanted to use negative-indexing this could be done:

如果你真的想使用负索引,可以这样做:

g[-which(rownames(g) %in% remove), ]

... however it has a nasty potential erroneous result that arises when there are not any rownames in the target vector. The result may be no values returned.

…然而,当目标向量中没有任何行名时,就会出现令人讨厌的潜在错误结果。结果可能是没有返回值。

#2


7  

You cannot negative index a character vector when indexing. Turn your vector remove into a boolean. I've defined a function

索引字符向量时不能为负索引。将矢量移动到布尔值。我已经定义了一个函数

`%notin%` <- function(x,y) !(x %in% y) 

which can then be used as such: g[rownames(g) %notin% remove ,]

然后可以这样使用:g[rowname (g) %notin% remove,]

#3


3  

I use "setdiff" as follows:

我使用“setdiff”如下:

g[setdiff(rownames(g),remove),]