R/test.R

Defines functions test

test <- function(value, dtype) {
  # Test if a value is an instance of type `dtype`.
  # 
  # Arguments:
  #   value {char} -- value to test
  #   dtype {char} -- one of c('logical', 'date', 'numeric', 'char')
  # 
  # Returns:
  #   {logical}
  
  stopifnot(dtype %in% c('logical', 'date', 'numeric', 'char'))
  
  tryCatch({
    if (dtype == "logical") {
      if (tolower(value) %in% c("true", "t", "yes", "y", "false", "no", "n")) {
        return(TRUE)
      } else {
        return(FALSE)
      }
    } else if (dtype == "date") {
      test = as.Date(value)
    } else if (dtype == "numeric") {
      test = suppressWarnings(as.numeric(value))
      if (is.na(test)) { return(FALSE) } else { return(TRUE) }
    } else if (dtype == "char") {
      test = suppressWarnings(as.character(value))
      if (is.na(test)) { return(FALSE) } else { return(TRUE) }
    }
    return(TRUE)
  }, error = function(e) {
    return(FALSE)
  })
}
tsouchlarakis/rdoni documentation built on Sept. 16, 2019, 8:53 p.m.