R中将稀疏矩阵转换为数据框

27

我有一个稀疏矩阵

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 循环 之外,快速将此矩阵转换为列表的方法是什么?

Origin Destination Weight
AAA AAE 4
AAL AAN 5

注意:我只需要获取重量大于零的起点和终点。


1
library(reshape2); dcast(Origin ~ Destination, data = dat, subset = Weight != 0) - Chase
3个回答

38

使用 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

这并没有返回稀疏矩阵的原始模式。 - cloudscomputes

14

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

as.matrix函数将稀疏矩阵转换为密集矩阵,如果矩阵不太大的话:-)。然后您可以将其转换为数据框。

(mat是@flodel答案中的示例dgCMatrix)


0
df <- as.data.frame(as.matrix(m))

如果稀疏矩阵太大,我发现分块转换是可行的。请修改下面的“step_size”变量以更改块大小。如果您想按行而不是按列进行分块,请将“ncol”和“cbind”更改为“nrow”和“rbind”。
large_matrix_to_df <- function(m){
  
  iter = 1
  step_size = 5000
  
  output = NULL
  
  while(iter + step_size < ncol(m)){
    print(iter)
    add_output = data.frame(as.matrix(m[,iter:(iter+step_size-1)]))

    if(is.null(output)){
      output = add_output
    }else{
      output = cbind(output,add_output)
    }
    
    iter = iter + step_size
  }

  add_output = data.frame(as.matrix(m[,iter:ncol(m)]))
  output = cbind(output,add_output)
  
  return (output)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接