Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 147

Digression – The speed of loops

Оглавление

The code base of R has been improved a lot and loops are faster than they used to be, however, there can still be a significant time difference between using a loop or using a pre-implemented function.

n <- 107 v1 <- 1:n # -- using vector arithmetic t0 <- Sys.time() v2 <- v1 * 2 t1 <- Sys.time() - t0 print(t1) ## Time difference of 0.06459093 secs # -- using a for loop rm(v2) v2 <- c() t0 <- Sys.time() for (k in v1) v2[k] <- v1[k] * 2 t2 <- Sys.time() - t0 print(t2) ## Time difference of 3.053826 secs # t1 and t2 are difftime objects and only differences # are defined. # To get the quotient, we need to coerce them to numeric. T_rel <- as.numeric(t2, units = “secs”) / as.numeric(t1, units = “secs”) T_rel ## [1] 47.27949

Note that in our simple experiment the for-loop is 47.3 times slower than the vector operation! So, use operators at the highest level (vectors, matrices, etc) and especially do an effort to understand the apply-family functions (see Chapter 4.3.5 “Arrays” on page 50) or their tidyverse equivalents: the map-family of functions of the package purrr. An example for the apply-family can be found in Chapter 22.2.6 on page 513 and one for the mapfamily is in Chapter 19.3 on page 459.

The Big R-Book

Подняться наверх