如何通过行名而不是​​数字索引删除矩阵的行? [英] How to remove rows of a matrix by row name, rather than numerical index?

查看:54
本文介绍了如何通过行名而不是​​数字索引删除矩阵的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有矩阵 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,]

-remove错误:一元运算符的参数无效

Error in -remove : invalid argument to unary operator

是否有一种简单的方法可以做我想做的事情(从矩阵 g 中删除矢量'remove'中引用的ID?

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[-(1:2), ],我需要能够删除一大堆我要删除的行拥有ID-d.

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.

推荐答案

使用索引时,不能使用负"字符向量.您可以使用%in%

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.

这篇关于如何通过行名而不是​​数字索引删除矩阵的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆