R: convert matrix to three columns

I have a matrix in R. Each i , j entry is an estimate, and the names of the growths and code names are identifiers.

Instead of a matrix, I just need a 3-column matrix that has: i , j , score

Now I am using nested for loops. How:

 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 it is very inefficient, I think ... I am sure that there is a better way that I am not good enough yet with R. Thoughts?

+4
source share
2 answers

If I understand you correctly, you need to smooth the matrix.
You can use as.vector and rep to add id columns, for example.

 m = cbind(c(1,2,3),c(4,5,6),c(7,8,9)) row.names(m) = c('R1','R2','R3') colnames(m) = c('C1','C2','C3') d <- data.frame(i=rep(row.names(m),ncol(m)), j=rep(colnames(m),each=nrow(m)), score=as.vector(m)) 

Result:

 > m C1 C2 C3 R1 1 4 7 R2 2 5 8 R3 3 6 9 > d ij score 1 R1 C1 1 2 R2 C1 2 3 R3 C1 3 4 R1 C2 4 5 R2 C2 5 6 R3 C2 6 7 R1 C3 7 8 R2 C3 8 9 R3 C3 9 

Note that this code converts the matrix to data.frame , since row and column names can be string, and you cannot have a matrix with a different column type.
If you are sure that all row and column names are numbers, you can force them on the matrix.

+6
source

If you first convert your matrix to a table (with as.table ) and then to a data frame ( as.data.frame ), then it will do what you ask for. A simple example:

 > tmp <- matrix( 1:12, 3 ) > dimnames(tmp) <- list( letters[1:3], LETTERS[4:7] ) > as.data.frame( as.table( tmp ) ) Var1 Var2 Freq 1 a D 1 2 b D 2 3 c D 3 4 a E 4 5 b E 5 6 c E 6 7 a F 7 8 b F 8 9 c F 9 10 a G 10 11 b G 11 12 c G 12 
+6
source

Source: https://habr.com/ru/post/1403975/


All Articles