Skip to content

Commit

Permalink
Warn when periodicity() called on date-time with NA
Browse files Browse the repository at this point in the history
Remove NA values to continue processing. Otherwise the uninformative
error below will be thrown:

    Error in try.xts(x, error = "'x' needs to be timeBased or xtsible") :
      'x' needs to be timeBased or xtsible

Closes #289.
  • Loading branch information
joshuaulrich committed Feb 26, 2023
1 parent a3fe6c7 commit 2ec118b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
12 changes: 10 additions & 2 deletions R/periodicity.R
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,16 @@ time.frequency <- function(x) {
}

periodicity <- function(x, ...) {
if( timeBased(x) || !is.xts(x) )
x <- try.xts(x, error='\'x\' needs to be timeBased or xtsible')
if( timeBased(x) ) {
if( anyNA(x) ) {
warning("removing NA in 'x' to calculate periodicity")
x <- x[!is.na(x)]
}
x <- try.xts(x, error = "cannot convert 'x' to xts")
}
if (!is.xts(x)) {
x <- try.xts(x, error = "cannot convert 'x' to xts")
}

n <- length(.index(x))
if( n < 2 ) {
Expand Down
4 changes: 4 additions & 0 deletions inst/tinytest/test-periodicity.R
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,7 @@ expect_identical(test07$units, result07$units, info = do.call(paste, c(list(info
expect_identical(test08$units, result08$units, info = do.call(paste, c(list(info_msg), test08)))
expect_identical(test09$units, result09$units, info = do.call(paste, c(list(info_msg), test09)))
expect_identical(test10$units, result10$units, info = do.call(paste, c(list(info_msg), test10)))

info_msg <- "periodicity warns when 'x' is time-based and contains NA"
x <- .Date(c(1:5, NA, 7:10))
expect_warning(periodicity(x), info = info_msg)

0 comments on commit 2ec118b

Please sign in to comment.