Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Obtain vector of non-zero elements in sparse matrix, keeping both column and row names

Suppose I have the following matrix:

mat <- matrix(data = c(1, 2, 3, 0, 0, 0, 0, 0, 0, 
                       0, 0, 0, 2, 3, 4, 0, 0, 0,
                       0, 0, 0, 0, 0, 0, 5, 6, 7),
              nrow = 9, 
              dimnames = list(c(paste0("x", 1:3),
                                paste0("y", 1:3),
                                paste0("z", 1:3)),
                              c("a", "b", "c")))

   a b c
x1 1 0 0
x2 2 0 0
x3 3 0 0
y1 0 2 0
y2 0 3 0
y3 0 4 0
z1 0 0 5
z2 0 0 6
z3 0 0 7

Instead of a matrix, I want a vector only keeping the non-zero elements.

red <- apply(mat, 1, function(x) x[x != 0])
x1 x2 x3 y1 y2 y3 z1 z2 z3 
 1  2  3  2  3  4  5  6  7 

Is there a way to have the reduced vector keep the column names as well? Preferably the pattern "colname + character + rowname". See desired output below. Note that we do not know in advance how many columns/rows there will be, nor how they are named.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a=x1 a=x2 a=x3 b=y1 b=y2 b=y3 c=z1 c=z2 c=z3 
 1    2    3    2    3    4    5    6    7 

Thank you in advance!

>Solution :

A base solution with which(..., arr.ind = TRUE):

ind <- which(mat != 0, arr.ind = TRUE)
setNames(
  mat[ind],
  paste(colnames(mat)[ind[, 'col']], rownames(mat)[ind[, 'row']], sep = '=')
)

# a=x1 a=x2 a=x3 b=y1 b=y2 b=y3 c=z1 c=z2 c=z3 
#    1    2    3    2    3    4    5    6    7
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading