Effektiv R-kod
Colin Gillespie
Jumping Rivers & Newcastle University
Mål
rnorm(4)
-0.7247 0.2502 0.3510 0.6919
mean(c(36, 48))
42
library(microbenchmark)
n <- 1e6
x <- vector("numeric", n)
microbenchmark(
x <- rnorm(n),
{
for(i in seq_along(x))
x[i] <- rnorm(1)
},
times = 10
)
# Unit: milliseconds
# expr lq mean uq cld
# rnorm(n) 60 70 80 a
# Looping 2600 2700 2800 b
## Output trimmed for presentation
Jämför
x <- vector("numeric", n)
for(i in seq_along(x))
x[i] <- rnorm(1)
med
x <- rnorm(n)
x <- vector("numeric", n)
for(i in seq_along(x))
x[i] <- rnorm(1)
x <- vector("numeric", n)
rnorm()rnorm()Den andra regeln i R-klubben: använd en vektoriserad lösning när det är möjligt.
Effektiv R-kod