R中的数据帧的稀疏矩阵 [英] Sparse matrix to a data frame in R

查看:85
本文介绍了R中的数据帧的稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个稀疏矩阵

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除外):

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

注意:我只需要获取重量> 0的起点和终点

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

推荐答案

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

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

这篇关于R中的数据帧的稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆