Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Rearrange matrix into three columns

Tags:

r

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?

like image 275
JoshDG Avatar asked Mar 28 '12 18:03

JoshDG


1 Answers

If I understand you correctly, you need to flatten the matrix.
You can use as.vector and rep to add the id columns e.g. :

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
   i  j 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

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.

like image 149
digEmAll Avatar answered Oct 03 '22 15:10

digEmAll