首页 > 解决方案 > 从R中的文本构造一个稀疏矩阵

问题描述

我需要在 R 中构造一个 30915r * 31193c 矩阵。我有一个 csv 文件,如下所示:

1:1 2:116 3:65 6:1 12:1 10025:1 25091:1 25836:1 31193:1
1:1 2:70 3:50 11:1 12:1 10025:1 23671:1
1:1 2:42 6:1 12:1 10025:1 10378:1 24213:1
1:1 2:105 3:73 11:1 12:1 10025:1 22547:1
...[total 30915 lines]

行号是行索引。在每一行,冒号前的每个数字都是列索引。冒号后面的数字就是值。文中未显示的所有其他索引值均为 0。

如何将 csv 文件转换为 R 中的稀疏矩阵?

谢谢您的帮助!

标签: rsparse-matrix

解决方案


dd = readLines("your_file.ext")

# should give you something like this:
dd = c("1:1 2:116 3:65 6:1 12:1 10025:1 25091:1 25836:1 31193:1",
"1:1 2:70 3:50 11:1 12:1 10025:1 23671:1",
"1:1 2:42 6:1 12:1 10025:1 10378:1 24213:1",
"1:1 2:105 3:73 11:1 12:1 10025:1 22547:1")

dd = strsplit(dd, split = " ", fixed = TRUE)
dd = sapply(dd, function(x) as.integer(unlist(strsplit(x, split = ":", fixed = TRUE))))
col_val = matrix(unlist(dd), ncol = 2, byrow = T)
row = rep(seq_along(dd), lengths(dd) / 2)
M = sparseMatrix(i = row, j = col_val[, 1], x = col_val[, 2])
M
# 4 x 31193 sparse Matrix of class "dgCMatrix"
#                                                                                                            
# [1,] 1 116 65 . . 1 . . . . . 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# [2,] 1  70 50 . . . . . . . 1 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# [3,] 1  42  . . . 1 . . . . . 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
# [4,] 1 105 73 . . . . . . . 1 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
#            
# [1,] ......
# [2,] ......
# [3,] ......
# [4,] ......
# 
#  .....suppressing columns in show(); maybe adjust 'options(max.print= *, width = *)'
#  ..............................

推荐阅读