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

后端 未结 3 2188
渐次进展
渐次进展 2020-12-02 23:07

I have matrix g:

> g[1:5,1:5]
        rs7510853 rs10154488 rs12159982 rs2844887 rs2844888
NA06985 \"CC\"      \"CC\"       \"CC\"       \         


        
相关标签:
3条回答
  • 2020-12-02 23:17

    I use "setdiff" as follows:

    g[setdiff(rownames(g),remove),]
    
    0 讨论(0)
  • 2020-12-02 23:32

    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.

    0 讨论(0)
  • 2020-12-02 23:33

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

    0 讨论(0)
提交回复
热议问题