การเขียน R Code อย่างมีประสิทธิภาพ
Colin Gillespie
Jumping Rivers & Newcastle University
เป้าหมาย
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
เปรียบเทียบ
x <- vector("numeric", n)
for(i in seq_along(x))
x[i] <- rnorm(1)
กับ
x <- rnorm(n)
x <- vector("numeric", n)
for(i in seq_along(x))
x[i] <- rnorm(1)
x <- vector("numeric", n)
rnorm() หนึ่งล้านครั้งrnorm() เพียงครั้งเดียวกฎข้อที่สองของ R club: ใช้แนวทาง vectorized ทุกครั้งที่ทำได้
การเขียน R Code อย่างมีประสิทธิภาพ