# compare code speed between using a loop, or the mean() function
library(data.table)
library(dplyr)
tmr <- data.table() # Initialize timer
vec <- rnorm(1e6) # Example vector
tmr <- timer(tmr, method = "loop") # timeStamp : 1st step =================
total <- 0
for (i in seq_along(vec)) total <- total + vec[i]
mean_loop <- total / length(vec)
tmr <- timer(tmr, method = "mean()") # timeStamp : 1st step =================
mean_func <- mean(vec)
tmr <- timer(tmr, end = TRUE) # timeStamp : close timer ==============
t_step1 <- tmr[method == "loop"]$dt_num
t_step2 <- tmr[method == "mean()"]$dt_num
diff_pc <- (t_step2/t_step1 - 1) * 100
diff_txt <- format(diff_pc, nsmall = 0, digits = 1)
# view speed difference
print(tmr %>% select(-matches("_num$")))
paste0("speed difference : ", diff_txt, "%")
Run the code above in your browser using DataLab