Skip to content

Instantly share code, notes, and snippets.

@privefl
Created July 13, 2018 08:51
Show Gist options
  • Save privefl/1895694804bf9c91a28dd85d3ebf953d to your computer and use it in GitHub Desktop.
Save privefl/1895694804bf9c91a28dd85d3ebf953d to your computer and use it in GitHub Desktop.
Example of efficiently using "`apply`" with a sparse matrix in R.
library(Matrix)
X <- rsparsematrix(1e4, 1e4, density = 0.01)
system.time(
test <- apply(X, 1, mean)
)
system.time(
test2 <- rowMeans(X)
)
apply1_sp <- function(X, FUN) {
res <- numeric(nrow(X))
X2 <- as(X, "dgTMatrix")
tmp <- tapply(X2@x, X2@i, FUN)
res[as.integer(names(tmp)) + 1] <- tmp
res
}
system.time(
test3 <- apply1_sp(X, sum) / ncol(X)
)
stopifnot(isTRUE(all.equal(test3, test)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment