ある分析を何回か繰り返し,その結果を保存しておくという例
> f = function() {lm(Ozone ~ Temp, aq[sample(nrow(aq), 100, replace=TRUE),])}
> f1 = function() rlply(100, f)
> set.seed(1); ans1 = f1(); head(ans1, 2)
[[1]]
Call:
lm(formula = Ozone ~ Temp, data = aq[sample(nrow(aq), 100, replace = TRUE),
])
Coefficients:
(Intercept) Temp
-153.799 2.559
[[2]]
Call:
lm(formula = Ozone ~ Temp, data = aq[sample(nrow(aq), 100, replace = TRUE),
])
Coefficients:
(Intercept) Temp
-147.962 2.418
>
> f2 = function() lapply(1:100, function(i) f())
> set.seed(1); ans2 = f2(); head(ans2, 2)
[[1]]
Call:
lm(formula = Ozone ~ Temp, data = aq[sample(nrow(aq), 100, replace = TRUE),
])
Coefficients:
(Intercept) Temp
-153.799 2.559
[[2]]
Call:
lm(formula = Ozone ~ Temp, data = aq[sample(nrow(aq), 100, replace = TRUE),
])
Coefficients:
(Intercept) Temp
-147.962 2.418
>
> # lm の結果が全部がほしいわけではないというならば以下のように
> # rlply の定義の主要部は replicate とほとんど同じ
> f3 = function() replicate(100, f()$coefficients[2])
> set.seed(1); ans3 = f3(); head(ans3, 2)
Temp Temp
2.559170 2.418056
>
> # 結果的にも,引き分け(replicate が若干速い?)
> benchmark(f1(), f2(), f3(), columns=c("test", "replications", "elapsed", "relative", "user.self", "sys.self"), replications=100, order=NULL)
test replications elapsed relative user.self sys.self
1 f1() 100 15.485 1.063 15.488 0.120
2 f2() 100 15.295 1.050 15.298 0.090
3 f3() 100 14.572 1.000 14.582 0.078
※コメント投稿者のブログIDはブログ作成者のみに通知されます