简体   繁体   English

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

[英]How to remove rows of a matrix by row name, rather than numerical index?

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 -remove中的错误:一元运算符的无效参数

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?

Note: 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。

When working with indexing, you cannot use "negative" character vectors. 使用索引时,不能使用“负”字符向量。 You can convert to logical with %in% 您可以使用%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. ...但是当目标向量中没有任何rownames时,它会产生令人讨厌的潜在错误结果。 The result may be no values returned. 结果可能是没有返回值。

You cannot negative index a character vector when indexing. 索引时不能对字符向量进行否定索引。 Turn your vector remove into a boolean. 将你的矢量remove转换为布尔值。 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[rownames(g) %notin% remove ,]

我使用“setdiff”如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM