3

我想知道有没有一种方法可以在 R 中的(来自包)上执行某种apply功能来切割等 数组上的列?sparseMatrixMatrixk

并且是否仅将列中大于 0 的那些元素划分为组

对于小sparseMatrix代码看起来像这样,但我敢打赌它在更大的矩阵上不会有效。

library(Matrix)
i <- c(1:8, rep(8,7)); j <- c(1:8, 1:7); x <- c(8 * (1:8),1:7)
(A <- sparseMatrix(i, j, x = x))
#8 x 8 sparse Matrix of class "dgCMatrix"

[1,] 8  .  .  .  .  .  .  .
[2,] . 16  .  .  .  .  .  .
[3,] .  . 24  .  .  .  .  .
[4,] .  .  . 32  .  .  .  .
[5,] .  .  .  . 40  .  .  .
[6,] .  .  .  .  . 48  .  .
[7,] .  .  .  .  .  . 56  .
[8,] 1  2  3  4  5  6  7 64
> 
"
> k<- 2
> apply(A,2,function(element){
+   cut(element,
+   k)})
     [,1]         [,2]         [,3]          [,4]          [,5]         [,6]          [,7]          [,8]         
[1,] "(4,8.01]"   "(-0.016,8]" "(-0.024,12]" "(-0.032,16]" "(-0.04,20]" "(-0.048,24]" "(-0.056,28]" "(-0.064,32]"
[2,] "(-0.008,4]" "(8,16]"     "(-0.024,12]" "(-0.032,16]" "(-0.04,20]" "(-0.048,24]" "(-0.056,28]" "(-0.064,32]"
[3,] "(-0.008,4]" "(-0.016,8]" "(12,24]"     "(-0.032,16]" "(-0.04,20]" "(-0.048,24]" "(-0.056,28]" "(-0.064,32]"
[4,] "(-0.008,4]" "(-0.016,8]" "(-0.024,12]" "(16,32]"     "(-0.04,20]" "(-0.048,24]" "(-0.056,28]" "(-0.064,32]"
[5,] "(-0.008,4]" "(-0.016,8]" "(-0.024,12]" "(-0.032,16]" "(20,40]"    "(-0.048,24]" "(-0.056,28]" "(-0.064,32]"
[6,] "(-0.008,4]" "(-0.016,8]" "(-0.024,12]" "(-0.032,16]" "(-0.04,20]" "(24,48]"     "(-0.056,28]" "(-0.064,32]"
[7,] "(-0.008,4]" "(-0.016,8]" "(-0.024,12]" "(-0.032,16]" "(-0.04,20]" "(-0.048,24]" "(28,56.1]"   "(-0.064,32]"
[8,] "(-0.008,4]" "(-0.016,8]" "(-0.024,12]" "(-0.032,16]" "(-0.04,20]" "(-0.048,24]" "(-0.056,28]" "(32,64.1]"  
4

1 回答 1

0

三种可能的方法:

  1. 将稀疏矩阵转换为data.table
  2. 转换为 asimple_triplet_matrix并使用包中的rollup函数slam
  3. 将稀疏矩阵转换为列列表并使用vapply

选项 1 和 3 支持列上的并行处理。选项 3 的依赖项最少。选项 3的实现作为quminorm包的一部分提供。如果我有时间,我可能会在未来将它拆分成一个单独的包。请注意,对于还需要零值的函数,最好的方法是使用colapply_simple_triplet_matrixpackage中的函数slam

这是一个在速度和内存消耗方面比较各种不同方案的小插图。

于 2020-07-27T00:32:05.337 回答