Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

r - How to remove rows of a matrix by row name, rather than numerical index?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...