申请R中的sparseMatrix

时间:2015-04-27 16:28:15

标签: r sparse-matrix sparse-columns

我想知道有没有办法在R中的apply(来自sparseMatrix包)上执行某种Matrix函数来剪切k上的列 等众群体?

是否仅将组中的那些元素划分为大于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]"  

1 个答案:

答案 0 :(得分:0)

三种可能的方法:

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

选项1和3支持对列的并行处理。选项3的依赖关系最少。选项3的implementation作为quminorm软件包的一部分提供。如果我有时间,将来可能会把它分解成一个单独的程序包。请注意,对于也需要零值的函数,最好的方法是使用程序包colapply_simple_triplet_matrix中的函数slam

这里是vignette,它在速度和内存消耗方面比较了各种不同的方案。