Sparse matrix to a data frame in R

前端 未结 2 433
长情又很酷
长情又很酷 2020-11-30 06:56

I have a sparse matrix

Formal class \'dgCMatrix\' [package \"Matrix\"] with 6 slots
  ..@ i       : int [1:37674] 1836 2297 108 472 1735 1899 2129 2131 5 67         


        
相关标签:
2条回答
  • 2020-11-30 07:26

    Using summary, here is an example:

    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
    
    0 讨论(0)
  • 2020-11-30 07:26

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

    as.matrix will turn the sparse matrix to a dense matrix, if it is not too large:-) Then you can convert it to a data frame.

    (mat is the example dgCMatrix from @flodel 's answer)

    0 讨论(0)
提交回复
热议问题