尝试这个。它连接矩阵输出,然后在成对summary
分组后取最大值。(i, j)
从某种意义上说,它也是可泛化的,您可以执行任何类型的元素操作,只需替换max
为您选择的函数(或编写一个带FUN
参数的通用函数)。
pmax.sparse <- function(..., na.rm = FALSE) {
# check that all matrices have conforming sizes
num.rows <- unique(sapply(list(...), nrow))
num.cols <- unique(sapply(list(...), ncol))
stopifnot(length(num.rows) == 1)
stopifnot(length(num.cols) == 1)
cat.summary <- do.call(rbind, lapply(list(...), summary))
out.summary <- aggregate(x ~ i + j, data = cat.summary, max, na.rm)
sparseMatrix(i = out.summary$i,
j = out.summary$j,
x = out.summary$x,
dims = c(num.rows, num.cols))
}
如果您的矩阵太大且不够稀疏以至于此代码对于您的需要来说太慢了,我会考虑使用类似的方法data.table
。
这是一个应用示例:
N <- 1000000
n <- 10000
M1 <- sparseMatrix(i = sample(N,n), j = sample(N,n), x = runif(n), dims = c(N,N))
M2 <- sparseMatrix(i = sample(N,n), j = sample(N,n), x = runif(n), dims = c(N,N))
M3 <- sparseMatrix(i = sample(N,n), j = sample(N,n), x = runif(n), dims = c(N,N))
system.time(p <- pmax.sparse(M1,M2,M3))
# user system elapsed
# 2.58 0.06 2.65
另一个建议的解决方案失败了:
Error in .class1(object) :
Cholmod error 'problem too large' at file ../Core/cholmod_dense.c, line 106