Skip to content

Commit

Permalink
[Fix tidyverse#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
  • Loading branch information
ctbrown committed Oct 24, 2016
1 parent 14774c8 commit 2e4a516
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
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 ) &&
all( minute(na.omit(ans)) == 0 ) &&
all( 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 2e4a516

Please sign in to comment.