Nirke
Nirke

Reputation: 173

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?

Upvotes: 6

Views: 9697

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99351

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.

Upvotes: 9

Related Questions