Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R convert matrix to list

I have a large matrix

> str(distMatrix)
 num [1:551, 1:551] 0 6 5 Inf 5 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:551] "+" "ABRAHAM" "ACTS" "ADVANCE" ...
  ..$ : chr [1:551] "+" "ABRAHAM" "ACTS" "ADVANCE" ...

which contains numeric values. I need to gather all numeric values into ONE long list (for acquiring distribution). Currently what I have:

for(i in 1:dim(distMatrix)[[1]]){
    for (j in 1:1:dim(distMatrix)[[1]]){
      distances[length(distances)+1] <- distMatrix[i,j]
    }  
  }

However, that takes forever. Can anyone suggest a faster way?

like image 686
Nirke Avatar asked Mar 24 '15 02:03

Nirke


1 Answers

To turn a matrix into a list, the length of which is the same as the number of elements in the matrix, you can simply do

as.list(distMatrix)

This goes down the columns, but you can use the transpose

as.list(t(distMatrix))

to make it go across the rows. Since your matrix is 551x551 it should be sufficiently efficient.

like image 140
Rich Scriven Avatar answered Sep 21 '22 12:09

Rich Scriven