I have a matrix in R. Each entry i,j is a score and the rownames and colnames are ids.
Instead of the matrix I just want a 3 column matrix that has: i,j,score
Right now I’m using nested for loops. Like:
for(i in rownames(g))
{
print(which(rownames(g)==i))
for(j in colnames(g))
{
cur.vector<-c(cur.ref, i, j, g[rownames(g) %in% i,colnames(g) %in% j])
rbind(new.file,cur.vector)->new.file
}
}
But thats very inefficient I think…I’m sure there’s a better way I’m just not good enough with R yet.
Thoughts?
If I understand you correctly, you need to flatten the matrix.
You can use
as.vectorandrepto add the id columns e.g. :Result:
Please, note that this code converts a matrix into a
data.frame, since the row and col names can be string and you can’t have a matrix with different column type.If you are sure that all row and col names are numbers, you can coerced it to a matrix.