Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

Sparse matrix to a data frame in R

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 ...
  ..@ 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()

What is a fast way to convert this matrix to a list as (except for a for loop):

Origin Destination Weight
AAA AAE 4
AAL AAN 5

Note: I only need to get the Origin and Destination for Weight>0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...