稀疏矩阵中的R的数据帧(Sparse matrix to a data frame in R)

2019-06-17 19:14发布

我有一个稀疏矩阵

Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:37674] 1836 2297 108 472 1735 1899 2129 2131 5 67 ...
  ..@ p       : int [1:3417] 0 2 8 22 25 35 44 45 45 47 ...
  ..@ Dim     : int [1:2] 3416 3416
  ..@ Dimnames:List of 2
  .. ..$ : chr [1:3416] "AAA" "AAE" "AAL" "AAN" ...
  .. ..$ : chr [1:3416] "AAA" "AAE" "AAL" "AAN" ...
  ..@ x       : num [1:37674] 1 1 1 1 1 1 1 1 1 1 ...
  ..@ factors : list()

什么是这个矩阵转换成一个列表,(除了一个快速的方式for loop ):

Origin Destination Weight
AAA AAE 4
AAL AAN 5

注:我只需要得到始发地和目的地的重量> 0

Answer 1:

使用summary ,下面是一个例子:

mat <- Matrix(data = c(1, 0, 2, 0, 0, 3, 4, 0, 0), nrow = 3, ncol = 3,
              dimnames = list(Origin      = c("A", "B", "C"),
                              Destination = c("X", "Y", "Z")),
              sparse = TRUE)
mat
# 3 x 3 sparse Matrix of class "dgCMatrix"
#    Destination
#     X Y Z
#   A 1 . 4
#   B . . .
#   C 2 3 .

summ <- summary(mat)
summ
# 3 x 3 sparse Matrix of class "dgCMatrix", with 4 entries 
#   i j x
# 1 1 1 1
# 2 3 1 2
# 3 3 2 3
# 4 1 3 4

data.frame(Origin      = rownames(mat)[summ$i],
           Destination = colnames(mat)[summ$j],
           Weight      = summ$x)
#   Origin Destination Weight
# 1      A           X      1
# 2      C           X      2
# 3      C           Y      3
# 4      A           Z      4


Answer 2:

df <- as.data.frame(as.matrix(mat))

as.matrix将稀疏矩阵变成一个稠密矩阵,如果它不是太大:-)然后,你可以将其转换为数据帧。

mat是从@flodel的回答的例子dgCMatrix)



文章来源: Sparse matrix to a data frame in R