how to get row-column pairs from sparse matrix

Viewed 278

Say I have a sparse matrix M1

i<-c(1,5,2,4,2,2,8)
j<-c(2,5,3,2,4,2,4)
x<-rpois(7,2)
M1<-sparseMatrix(i,j,x=x)
rownames(M1) <- c("a", "b", "c", "d", "e", "f", "g", "h")
colnames(M1) <- c("L1", "L2", "L3", "L4", "L5")
M1

where M1 looks like:

8 x 5 sparse Matrix of class "dgCMatrix"
  L1 L2 L3 L4 L5
a  .  3  .  .  .
b  .  1  3  0  .
c  .  .  .  .  .
d  .  4  .  .  .
e  .  .  .  .  1
f  .  .  .  .  .
g  .  .  .  .  .
h  .  .  .  0  .

how would i make a set of interacting row-col pairs in a list that looks something like:

(a, L2)
(b, L2)
(b, L3)
(b, L4)
(d, L2)
(e, L5)
(h, L4)

Thanks!

2 Answers

Use which with arr.ind = TRUE on a logical matrix and extract the row names and column names based on the row/col index

i1 <- which(M1 > 0, arr.ind = TRUE)
library(dplyr)
tibble(rn = row.names(M1)[i1[,1]], cn = colnames(M1)[i1[,2]]) %>%
    arrange(rn) 

-ouptut

# A tibble: 7 x 2
  rn    cn   
  <chr> <chr>
1 a     L2   
2 b     L2   
3 b     L3   
4 b     L4   
5 d     L2   
6 e     L5   
7 h     L4   

You can use the code below

with(
  summary(t(M1)),
  data.frame(i = row.names(M1)[j], j = colnames(M1)[i])
)

which gives

  i  j
1 a L2
2 b L2
3 b L3
4 b L4
5 d L2
6 e L5
7 h L4
Related