Created
July 13, 2018 08:51
-
-
Save privefl/1895694804bf9c91a28dd85d3ebf953d to your computer and use it in GitHub Desktop.
Example of efficiently using "`apply`" with a sparse matrix in R.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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