-
Notifications
You must be signed in to change notification settings - Fork 117
/
helper-round-any.r
35 lines (33 loc) · 1.01 KB
/
helper-round-any.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#' Round to multiple of any number.
#'
#' @param x numeric or date-time (POSIXct) vector to round
#' @param accuracy number to round to; for POSIXct objects, a number of seconds
#' @param f rounding function: \code{\link{floor}}, \code{\link{ceiling}} or
#' \code{\link{round}}
#' @keywords manip
#' @export
#' @examples
#' round_any(135, 10)
#' round_any(135, 100)
#' round_any(135, 25)
#' round_any(135, 10, floor)
#' round_any(135, 100, floor)
#' round_any(135, 25, floor)
#' round_any(135, 10, ceiling)
#' round_any(135, 100, ceiling)
#' round_any(135, 25, ceiling)
#'
#' round_any(Sys.time() + 1:10, 5)
#' round_any(Sys.time() + 1:10, 5, floor)
#' round_any(Sys.time(), 3600)
round_any <- function(x, accuracy, f = round) {
UseMethod("round_any")
}
round_any.numeric <- function(x, accuracy, f = round) {
f(x / accuracy) * accuracy
}
round_any.POSIXct <- function(x, accuracy, f = round) {
tz <- format(x[1], "%Z")
xr <- round_any(as.numeric(x), accuracy, f)
as.POSIXct(xr, origin="1970-01-01 00:00.00 UTC", tz=tz)
}