r - 从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 中的稀疏矩阵?
谢谢您的帮助!
解决方案
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 = *)'
# ..............................
推荐阅读
- mysql - 如何在 /etc/mysql/my.cnf 中调整 InnoDB 性能
- google-api-php-client - 如何搜索我通过 Google Cloud Talent Solution API 添加的职位
- python - STT Watson Python“收到错误:[WinError 10014] 系统在尝试在调用中使用指针参数时检测到无效的指针地址”
- excel - 如何计算给定月份某个部门的员工人数?
- android - Android - 如何测试是否加载了正确的片段?
- gcc - gcc 标志重复和排序重要吗?
- c# - 使用 c# 从字符串中读取自定义标签值
- puredata - Pd补丁中可能存在的错误
- python - 当我从 Python Flask API 接收 JSON 时,Ajax Jquery 命中错误事件
- python - 遍历熊猫中的每一行的python脚本