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

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

问题描述

我有矩阵g:

>g[1:5,1:5]rs7510853 rs10154488 rs12159982 rs2844887 rs2844888NA06985CC"CC"CC"CC"CC"NA06991CC"CC"CC"CC"CC"NA06993CC"CC"CC"CC"CC"NA06994CC"CC"CC"CC"CC"NA07000 CC" CC" CC" CC" CC">行名(g)[1:2]->删除>消除[1] "NA06985" "NA06991">g[-删除,]

<块引用>

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

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

注意:这只是我真正想做的一个模型,请不要说只是做g[-(1:2), ],我需要能够删除我有 ID-d 的一大堆行.

解决方案

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

转换为逻辑

g[!rownames(g) %in% remove, ] # !是逻辑否定

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

g[-which(rownames(g) %in% remove), ] #which转换为数字,所以减号OK

... 然而,当目标向量中没有任何行名时,它会产生一个令人讨厌的潜在错误结果.结果可能没有返回值.

I have matrix 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?

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.

解决方案

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

g[!rownames(g) %in% remove, ]  # ! is logical negation

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

g[-which(rownames(g) %in% remove), ] #which converts to numeric, so minus sign OK

... 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天全站免登陆