Использование apply может дать вам некоторое увеличение скорости.
# How many rows?
n <- 1000
# How many samples from runif?
k <- 20
# Preallocate x
x <- double(n)
## Your loop
for(i in 1:n){
x[i] <- sum(runif(k))
}
## Using apply
## First create a matrix that has n rows and k columns
## then find the sum of the row.
x <- apply(matrix(runif(n*k), nrow=n), 1, sum)
Теперь проверьте скорость:
benchmark(
loop = expression(
for(i in 1:n){
x[i] <- sum(runif(k))
}
),
apply = expression(
x <- apply(matrix(runif(n*k), nrow=n), 1, sum)
)
)
# Result of benchmark
#
# test replications elapsed relative user.self sys.self user.child sys.child
#2 apply 100 1.08 1.000000 1.06 0.00 NA NA
#1 loop 100 1.69 1.564815 1.63 0.02 NA NA
Цикл длится дольше, чем применяется.