1. avoid data frame (from 2nd)
2. ifelse is slower than if () { } else { } (from 1st)
3. aovid using rbind, cbind in loops, predifine a NA array or matrix(from 2nd)
Examples:
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
## data frame and matrix comparison | |
> m <- matrix(nrow=2000, ncol =1) | |
> system.time(for (i in 1:2000) {m[i,1] <- 1}) | |
user system elapsed | |
0 0 0 | |
> m <- as.data.frame(m) | |
> system.time(for (i in 1:2000) {m[i,1] <- 1}) | |
user system elapsed | |
0.42 0.00 0.44 | |
## ifelse cbind | |
testifelse <- function(x) { | |
for(i in 1:x) { | |
tmp <- paste("out", i) | |
ifelse(i == 1, out <- tmp, out <- c(out, tmp)) | |
} | |
} | |
testif <- function(x) { | |
for(i in 1:x) { | |
tmp <- paste("out", i) | |
if (i == 1) { | |
out <- tmp | |
} else { | |
out <- c(out, tmp) | |
} | |
} | |
} | |
> system.time(testifelse(2000)) | |
user system elapsed | |
0.22 0.00 0.22 | |
> system.time(testif(2000)) | |
user system elapsed | |
0.11 0.00 0.11 | |
byarray <- function(x) { | |
out <- matrix(NA, nrow=x, ncol =1) | |
for(i in 1:x) { | |
tmp <- paste("out", i) | |
out[i,1] <- tmp | |
} | |
} | |
> system.time(byarray(2000)) | |
user system elapsed | |
0.06 0.00 0.06 |