我在 R 中有一个大的稀疏矩阵 (
dgCMatrix
),我想知道这个矩阵每个元素的指数。更准确地说,我想对矩阵的每个元素执行 1-exp(-x) 。不幸的是,当我在 R 中执行此操作时,有一个 sparse->dense coercion
需要大量时间和内存(请参见下面的示例)。
library(Matrix)
i <- sample(20000, 20000); j <- sample(20000, 20000); x <- 7 * (1:20000)
A <- sparseMatrix(i, j, x = x)
1 - exp(-A)
R 有没有办法避免这种强制?由于 1-exp(0) 为 0,也许可以保留稀疏性。
或许你可以尝试一下
A@x <- 1 - exp(-A@x)
这样您就只更新非稀疏条目。
对于非常小的
A@x
,我们可以使用
A@x <- -expm1(-A@x) # thanks for the comment from jblood94
或者只是简单地
A <- -expm1(-A) # thanks for the comment from Ben Bolker