Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

r - round_any equivalent for dplyr?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...