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

发布于 2024-12-06 17:17:48 字数 728 浏览 2 评论 0原文

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

有没有一种简单的方法可以完成我在这里想做的事情(从矩阵 g 中删除向量“remove”中引用的 ID?

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

阳光的暖冬 2024-12-13 17:17:48

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

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

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

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

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

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.

归途 2024-12-13 17:17:48

索引时不能对字符向量进行负索引。将向量 remove 转换为布尔值。我定义了一个函数

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

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

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 ,]

禾厶谷欠 2024-12-13 17:17:48

我使用“setdiff”如下:

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

I use "setdiff" as follows:

g[setdiff(rownames(g),remove),]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文