Skip to content

Commit

Permalink
Add date & datetime support to full_seq.
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed May 16, 2016
1 parent 890a8c4 commit 1b2767f
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 0 deletions.
3 changes: 3 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ S3method(extract_,grouped_df)
S3method(extract_,tbl_df)
S3method(fill_,data.frame)
S3method(fill_,grouped_df)
S3method(full_seq,Date)
S3method(full_seq,POSIXct)
S3method(full_seq,numeric)
S3method(gather_,data.frame)
S3method(gather_,grouped_df)
S3method(gather_,tbl_df)
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# tidyr 0.4.1.9000

* `full_seq()` now preserve attributes for dates and date/times (#156).

* Sequences generated by `full_seq()` no now longer need to start at 0.

* Moved in useful sample datasets from the DSR package.
Expand Down
21 changes: 21 additions & 0 deletions R/seq.R
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,31 @@
#' @examples
#' full_seq(c(1, 2, 4, 5, 10), 1)
full_seq <- function(x, period, tol = 1e-6) {
UseMethod("full_seq")
}

#' @export
full_seq.numeric <- function(x, period, tol = 1e-6) {
rng <- range(x, na.rm = TRUE)
if (any((x - rng[1]) %% period > tol)) {
stop("`x` is not a regular sequence.", call. = FALSE)
}

seq(rng[1], rng[2], by = period)
}

#' @export
full_seq.Date <- function(x, period, tol = 1e-6) {
restore(full_seq(as.numeric(x), period, tol), x)
}

#' @export
full_seq.POSIXct <- function(x, period, tol = 1e-6) {
restore(full_seq(as.numeric(x), period, tol), x)
}


restore <- function(old, new) {
mostattributes(new) <- attributes(old)
new
}
4 changes: 4 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,7 @@ regroup <- function(x, y, except) {
# Allows tests to work with either dplyr 0.4 (which ignores value of
# everything), and 0.5 which exports it as a proper function
everything <- function(...) dplyr::everything(...)

is_numeric <- function(x) {
typeof(x) %in% c("integer", "double")
}
8 changes: 8 additions & 0 deletions tests/testthat/test-full_seq.R
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,11 @@ test_that("sequences don't have to start at zero", {
test_that("full_seq fills in gaps", {
expect_equal(full_seq(c(1, 3), 1), c(1, 2, 3))
})

test_that("preserves attributes", {
x1 <- as.Date("2001-01-01") + c(0, 2)
x2 <- as.POSIXct(x1)

expect_s3_class(full_seq(x1, 2), "Date")
expect_s3_class(full_seq(x2, 86400), c("POSIXct", "POSIXt"))
})

0 comments on commit 1b2767f

Please sign in to comment.