for_loop <- function(n = 100L) {
result <- vector(mode = "integer", length = n)
for (i in 1L:n) {
result[i] = i * 17L
}
result
}
apply_loop <- function(n = 100L) {
result <- sapply(1L:n, function(i) i * 17L)
result
}
for_loop2 <- function(n = 100L) {
result <- NULL
for (i in 1L:n) {
result <- append(result, i * 17L)
}
result
}
dt_fun <- function(n = 100L) {
dt <- data.table(i = 1:n)
dt[, result := i * 17L ]
return(dt)
}
Testando:
> microbenchmark::microbenchmark(
+ z <- for_loop(),
+ w <- apply_loop(),
+ y <- for_loop2(),
+ x <- dt_fun()
+ )
Unit: microseconds
expr min lq mean median uq max neval
z <- for_loop() 7.587 8.9260 66.14092 11.1570 13.3885 5447.984 100
w <- apply_loop() 95.500 124.9540 186.48917 135.8870 151.5060 4673.271 100
y <- for_loop2() 172.258 205.5045 280.58838 222.0165 259.2795 4407.298 100
x <- dt_fun() 534.624 625.4390 733.75107 667.1640 716.6995 5493.057 100
> identical(z, w, y)
[1] TRUE