【问题标题】:Construct a sparse matrix from text in R从R中的文本构造一个稀疏矩阵
【发布时间】:2019-10-22 18:44:34
【问题描述】:

我需要在 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 中的稀疏矩阵?

感谢您的帮助!

【问题讨论】:

  • 行索引在哪里?是行号吗?
  • 是的,行索引就是行号。

标签: r sparse-matrix


【解决方案1】:
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 = *)'
#  ..............................

【讨论】:

  • 谢谢!该代码完美运行。你的回答真的为我节省了很多时间。 :)
猜你喜欢
  • 2013-11-29
  • 1970-01-01
  • 2021-09-22
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
  • 1970-01-01
相关资源
最近更新 更多