R: how to get row and column names of the true elements of a matrix?

前端 未结 3 991
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 02:06

I have a logical matrix x with named rows (\'a\' and \'b\') and named columns (\'10\', \'20\', \'30\', \'40\'). Let\'s say, this:

   10   20   3         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-12 02:28

    You didn't specify this, but your desired output will require that we assume that the result is in fact rectangular. Namely, that we don't get 3 column names for a and only 2 column names for b.

    I think this should get you started, at least:

    m <- structure(c(TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE),
    .Dim = c(2L, 4L), .Dimnames = list(c("a", "b"), c("10", "20", "30", "40")))
    
    rr <- rownames(m)[row(m)[which(m)]]
    cc <- colnames(m)[col(m)[which(m)]]
    
    dd <- data.frame(rr = rr,cc = cc)
    dd
    

    which returns the information you want, but in a safer "long" format, which won't choke on the non-rectangular case. Once there, you could re-organize it as you specified like this:

    library(plyr)
    ddply(dd,.(rr),function(x){ x$cc })
    

    but frankly that last bit I find really ugly, and I wouldn't be surprised if a better solution pops up if you wait a bit.

提交回复
热议问题