どこかにあるけど,そこは別に最適化をしようといっているのではないので,明示しない。
for は遅い。replicate も for と同じくらい。やはり,colMeans は速い。
という,つまらない結果だけど,掲示しておく。
> library(rbenchmark)
> n <- 100000
> x <- c(1, 2, 3, 5, 3, 4, 4, 7, 8, 10, 1)
> prog1 <- function() {
+ x.boot <- numeric(n)
+ for(i in 1:n){
+ x.boot[i] <- mean(sample(x, 10, replace=T))
+ }
+ hist(x.boot)
+ }
> prog2 <- function() {
+ x.boot <- replicate(n, mean(sample(x, 10, replace=TRUE)))
+ hist(x.boot)
+ }
> prog3 <- function() {
+ x <- matrix(sample(x, n*10, replace=TRUE), 10)
+ x.boot <- colMeans(x)
+ hist(x.boot)
+ }
> benchmark(prog1(), prog2(), prog3(), replications=10)
test replications elapsed relative user.self sys.self
1 prog1() 10 18.274 24.07642 18.140 0.195
2 prog2() 10 17.894 23.57576 17.792 0.147
3 prog3() 10 0.759 1.00000 0.697 0.054
※コメント投稿者のブログIDはブログ作成者のみに通知されます