简体   繁体   English

R将矩阵转换为列表

[英]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? 有谁能建议更快的方式?

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. 由于你的矩阵是551x551,它应该足够有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM