23

I am trying to make a switch to the "new" tidyverse ecosystem and try to avoid loading the old packages from Wickham et al. I used to rely my coding previously. I found round_any function from plyr useful in many cases where I needed custom rounding for plots, tables, etc. E.g.

x <- c(1.1, 1.0, 0.99, 0.1, 0.01, 0.001) 

library(plyr)    

round_any(x, 0.1, floor)
# [1] 1.1 1.0 0.9 0.1 0.0 0.0

Is there an equivalent for round_any function from plyr package in tidyverse?

Mikko
  • 7,530
  • 8
  • 55
  • 92
  • 3
    There isn't, but the function is quite simple, in this case `floor(x / 0.1) * 0.1`. To avoid loading the package, use the `::` notation: `plyr::round_any`. – Axeman Apr 26 '17 at 07:35
  • 2
    It seems that it was replaced by `ggplot2::cut_width`. See https://github.com/tidyverse/ggplot2/releases/tag/v2.0.0 – FlorianGD Apr 26 '17 at 07:38

1 Answers1

42

ggplot::cut_width as pointed to in one of the comments, does not even return a numeric vector, but a factor instead. So it is no real substitute.

Since round and not floor is the default rounding method, a custom replacement until a (dplyr solution may arrive) would be

round_any = function(x, accuracy, f=round){f(x/ accuracy) * accuracy}

This method could also be used directly from the plyr package which contains this implementation. However, be careful when loading plyr into a workspace which will cause naming conflicts when using dplyr as well.

Holger Brandl
  • 10,634
  • 3
  • 64
  • 63
  • 7
    You forgot to tell that you copied [this code literally from the `plyr` package](https://github.com/hadley/plyr/blob/34188a04f0e33c4115304cbcf40e5b1c7b85fedf/R/round-any.r#L28-L30). Of course it's not rocket science, but giving proper attribution is always a good idea. Still voted you up for sharing the simple code. Thanks! – MS Berends Apr 18 '20 at 17:38
  • Thanks @MSBerends for pointing out this regretful lack of source attribution. I've added it and also my original thoughts why I did not opt into using `plyr` directly at the time. – Holger Brandl Apr 20 '20 at 07:56