rloopsbreakmicrobenchmark

R - Simple loop not working: no loop for break/next, jumping to top level


I know this is probably an easy question but I am trying my best to learn and improve. When I try this code, it gives me the error: "no loop for break/next, jumping to top level". Could someone suggest why and help me? Thank you really much.

x_1 <- rnorm(100)
x_2 <- rnorm(10000)
x_3 <- rnorm(1000000)

to_evaluate <- list(x_1, x_2, x_3)

speed_test <- for (i in to_evaluate) {
  microbenchmark(mean_loop(i), mean_mat(i), mean(i))
} 
print(speed_test)

Code for mean_loop and mean_mat:

x <- c(1:11)

mean_loop <- function(x) {
  
  sum_of_x <- 0
  
  for(i in x){
    sum_of_x <- sum_of_x + x[i]
  }
  
  mean_of_x <- sum_of_x/length(x)
  return(mean_of_x)
}

mean_mat <- function(x) {
sum(diag(length(x))%*%x)/length(x)
}

The function microbenchmark (from the package microbenchmark) lets you measure how fast code runs. If you give it code to evaluate, it will evaluate it 100 times, and return summary statistics on how long the code took to run. If you give it multiple expressions, it will do this for each expression.


Solution

  • This works for me using the function definitions from the question -

    x_1 <- rnorm(10)
    x_2 <- rnorm(100)
    x_3 <- rnorm(1000)
    library(microbenchmark)
    to_evaluate <- list(x_1, x_2, x_3)
    
    result <- vector('list', length(to_evaluate))
    
    for (i in seq_along(to_evaluate)) {
      val <- to_evaluate[[i]]
      result[[i]] <- microbenchmark(mean_loop(val), mean_mat(val), mean(val))
    } 
    
    result
    
    #[[1]]
    #Unit: microseconds
    #           expr   min     lq    mean median    uq     max neval cld
    # mean_loop(val) 2.818 3.2495 7.62632  4.204 5.847  41.214   100   a
    #  mean_mat(val) 2.547 2.9765 7.90376  3.571 4.940  93.155   100   a
    #      mean(val) 1.896 2.1700 6.59605  2.818 4.204 116.467   100   a
    
    #[[2]]
    #Unit: microseconds
    #           expr    min      lq     mean median      uq     max neval cld
     #mean_loop(val) 49.368 89.8705 92.81099 92.820 99.6505 179.400   100   c
     # mean_mat(val) 18.968 50.7335 55.61163 52.987 55.5770 141.363   100  b 
     #     mean(val)  2.090  2.2815  3.87982  2.803  3.3115  33.779   100 a  
    
    #[[3]]
    #Unit: microseconds
    #           expr      min        lq       mean   median        uq       max neval cld
    # mean_loop(val) 1359.527 1511.9295 3312.36578 1835.326 2970.1350 16455.048   100   b
    #  mean_mat(val) 1713.178 2155.3815 4032.53143 2352.858 2739.6650 19783.264   100   b
    #      mean(val)    3.708    4.6695   16.39451   14.881   21.8355   162.184   100  a