assertr icon indicating copy to clipboard operation
assertr copied to clipboard

Feature request: check dates/times are within allowed date/time interval.

Open DrAndiLowe opened this issue 5 years ago • 1 comments

I simply copy-pasted the code for within_bounds:

# Hack of assertr::within_bounds:
within_interval <- function(lower.bound, 
                            upper.bound, 
                            include.lower = TRUE, 
                            include.upper = TRUE, 
                            allow.na = TRUE) {
  the_call <- deparse(sys.call())
  if(!(is.Date(lower.bound) && is.Date(upper.bound))) 
    stop("bounds must be numeric")
  if(lower.bound >= upper.bound) 
    stop("lower bound must be strictly lower than upper bound")
  fun <- function(x) {
    if(is.null(x)) 
      stop("bounds must be checked on non-null element")
    if(!is.Date(x)) 
      stop("bounds must only be checked on dates")
    lower.operator <- if(!include.lower) 
      `>`
    else `>=`
    upper.operator <- if(!include.upper) 
      `<`
    else `<=`
    if(allow.na) {
      return((lower.operator(x, lower.bound) & upper.operator(x, upper.bound)) | is.na(x))
    }
    return((lower.operator(x, lower.bound) & upper.operator(x, upper.bound)) & !(is.na(x)))
  }
  attr(fun, "assertr_vectorized") <- TRUE
  attr(fun, "call") <- the_call
  return(fun)
}

Probably it would be more elegant to adapt within_bounds to accept dates in addition to numeric, but this is what I'm using now.

DrAndiLowe avatar Sep 12 '19 17:09 DrAndiLowe

Hmm, I wonder if I can make within_bounds a generic function that dispatches differently if it's given dates. I think this is an excellent idea, by the way--thanks!

tonyfischetti avatar Oct 30 '19 22:10 tonyfischetti

Could this be resolved by simply removing the requirement that the input is numeric? Then, it would only require that the relative comparison operators are well defined, for example, that there is a valid comparison for <, <=, >=, and > between the inputs.

In essence, removing this line would generalize within_bounds():

https://github.com/ropensci/assertr/blob/355ef1df4735303e7b97e0585130d49758cbda0f/R/predicates.R#L95

billdenney avatar Feb 23 '23 02:02 billdenney