2010/02/25

Tips for enhance R code

After reading Writing Efficient Programs in R and R Code optimization and Packages Creation, 3 tips by now.
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:
## 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
view raw data frame hosted with ❤ by GitHub

CC Copyright

創用 CC 授權條款
本著作由Chunhung Chou製作,以創用CC 姓名標示-相同方式分享 3.0 Unported 授權條款釋出。