Skip to content

Commit

Permalink
[Fix #483] add_duration_to_date with leading NA
Browse files Browse the repository at this point in the history
* Fix code that had wrong test for date in ops-addition.r
* Added tests to test-ops-additions.R
* Update NEWS.md
  • Loading branch information
ctbrown authored and vspinu committed Nov 1, 2016
1 parent fce28cd commit d97d62d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
2 changes: 1 addition & 1 deletion NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Version 1.6.0.9000
* [#472](https://github.com/hadley/lubridate/pull/472) Printing method for duration doesn't throw format error on fractional seconds.
* [#475](https://github.com/hadley/lubridate/pull/475) character<> comparisons is no longer slow.
* [#486](https://github.com/hadley/lubridate/issues/486) ceiling_date handles `NA` properly.

* [#483](https://github.com/hadley/lubridate/pull/483) Fix add_duration_to_date error when duration first element is NA.

Version 1.6.0
=============
Expand Down
10 changes: 9 additions & 1 deletion R/ops-addition.r
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,16 @@ add_duration_to_date <- function(dur, date) {
if(is.Date(date)){
date <- as.POSIXct(date)
ans <- with_tz(date + dur@.Data, "UTC")
if (hour(ans) == 0 && minute(ans) == 0 && second(ans) == 0)

if ( all(is.na(ans) ) ) return(as.Date(ans)) # ALL NAs

if ( all( hour(na.omit(ans)) == 0 &
minute(na.omit(ans)) == 0 &
second(na.omit(ans)) == 0 )
) {
return(as.Date(ans))
}

return(ans)
}
new <- date + dur@.Data
Expand Down
23 changes: 23 additions & 0 deletions tests/testthat/test-ops-addition.R
Original file line number Diff line number Diff line change
Expand Up @@ -316,3 +316,26 @@ test_that("addition with period months and years returns NA when appropriate", {
expect_equal(leap - years(0:4), yrs2)

})

test_that("addition with durations containing NA", {

dt <- ymd(20161018)
dt_1 <- ymd(20161019)

dd_1na <- ddays(c(1,NA))
dd_na1 <- ddays(c(NA,1))
dd_nana <- ddays(c(NA,NA))

ans_1na <- add_duration_to_date( dd_1na, dt )
ans_na1 <- add_duration_to_date( dd_na1, dt )
ans_nana <- add_duration_to_date( dd_nana, dt )

expect_is( ans_1na, "Date")
expect_is( ans_na1, "Date")
expect_is( ans_nana, "Date")

expect_equal( ans_1na, c(dt_1,NA) )
expect_equal( ans_na1, rev(c(dt_1,NA)) )
expect_equal( ans_nana, as.Date(c(NA,NA)) )

})

0 comments on commit d97d62d

Please sign in to comment.