在下面的代码中,使用Matrix::colSums()
求和的结果与apply(, MARGIN = 2, FUN = sum)
不同。
library(Matrix)
# Initialise RNG
set.seed(3737)
# Parameters
nr <- 2000 # Number of rows
nc <- 5 # Number of columns
nz <- round(nr / 10) # Number of non-zero entries in each column
# Create a sparse matrix with given numbers or rows, columns and non-zero entries
a.sparse <- Matrix(0, nrow = nr, ncol =nc, sparse = TRUE)
for( c. in 1:nc ) {
a.sparse[sample(nr, nz), c.] <- rnorm(nz)
}
# Column sums are inconsistent between colSums and apply
colSums(a.sparse) - apply(a.sparse, MARGIN = 2, FUN = sum)
# Column sums are consistent between colSums and apply in dense case
a.dense <- as.matrix(a.sparse)
class(a.dense)
colSums(a.dense) - apply(a.dense, MARGIN = 2, FUN = sum)
例如,在colSums(a.sparse) - apply(a.sparse, MARGIN = 2, FUN = sum)
行中,我作为输出:
3.907985e-14 2.486900e-14 1.421085e-13 -1.421085e-13 0.000000e+00
但密集的情况下正常工作。任何人都可以阐明导致这里不一致的原因吗?该错误的数量级大于.Machine$double.eps
,并且正在导致我正在分析的软件不稳定。