gpt4 book ai didi

r - 稀疏矩阵到 R 中的数据框

转载 作者:行者123 更新时间:2023-12-03 13:22:52 26 4
gpt4 key购买 nike

我有一个稀疏矩阵

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

注意:我只需要获取 Weight>0 的 Origin 和 Destination

最佳答案

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

关于r - 稀疏矩阵到 R 中的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12029177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com