al-obrien / farrago

GNU General Public License v3.0
3 stars 0 forks source link

vectorized round_up_nice #4

Open al-obrien opened 3 months ago

al-obrien commented 3 months ago

Use matrix calculations to remove loop. This shows huge improvements when in thousands of values (95% decrease)

round_up_nice <- function(x, nice=c(1,2,4,5,6,8,10)) {

  floor_calc <- 10^floor(log10(x))

  # Find which nice val to use for each input
  exp_m <- outer(floor_calc, nice)
  nice_idx <- apply(x <= exp_m, 1, which.max)

  floor_calc * nice[nice_idx]
}
al-obrien commented 3 months ago

pmax() may also work, possibly faster, or matrixStats if can suffer for Imports