R/utils.R

Defines functions valid_length na_drop if_null try_numeric

Documented in if_null try_numeric

#' @importFrom magrittr %>%
#' @export
magrittr::`%>%`

#' Try for numeric
#'
#' Checks to see if the object can be converted, properly, to numeric
#'
#' @param object The object to test for numeric
#'
#' @return Either `object` or `as.numeric(object)`

try_numeric <- function(object) {
  stopifnot(!anyNA(object))
  res <- suppressWarnings(as.numeric(object))
  if(anyNA(res)) return(object) else return(res)
}


#' If null ...
#'
#' Returns a function or value if the `object` is null, otherwise the original the `object` .  Useful in functions when default values are provided for arg = NULL
#'
#' @param object The object to evaluate is.null
#' @param when_null An object, value, or code to evaluate when object is NULL
#' @return A non-NULL `object` or `when_null` if `object` is NULL

if_null <- function(object, when_null) {
  if(is.null(object)) return(eval(substitute(when_null, env = parent.frame())))
  object
}

na_drop <- function(x) {
  x[!is.na(x)]
}

valid_length <- function(x) {
  length(na_drop(x))
}
jmbarbone/qpm documentation built on July 25, 2020, 10:41 p.m.