1
votes

I'm trying to get dimnames couple from a matrix selection.

names<-c("n1", "n2", "n3")
mat<-matrix(0, nrow=length(names), ncol=length(names), dimnames=list(names, names))
mat[1,2]<-3
mat[3,2]<-6
mat

Output is :

   n1 n2 n3
n1  0  3  0
n2  0  0  0
n3  0  6  0

I would like to get all the couples greater than 0 :

n1,n2
n2,n3

The use of rownames and colnames give me NULL.

1
Try: matrix(rownames(mat)[which(mat!=0,arr.ind=TRUE)],ncol=2).nicola

1 Answers

2
votes

Try this:

matrix(rownames(mat)[which(mat!=0,arr.ind=TRUE)],ncol=2)
#     [,1] [,2]
#[1,] "n1" "n2"
#[2,] "n3" "n2"

Each row of the resulting matrix shows the indices of a different from zero element.