R/assert_cols_in.R

Defines functions assert_cols_in

Documented in assert_cols_in

#' Asserts That Columns are in Data Frame
#'
#' @param d data.frame
#' @param cols character vector of columns to check for
#'
#' @export
#' 
#' @examples
#' assert_cols_in(iris, c("Petal.Width", "Petal.Length")) # cols in, will do nothing
#' assert_cols_in(iris, c("x", "y")) # cols not in, will assert error
#' 

assert_cols_in <- function(d, cols){
  "Asserts that columns are in a data frame"
  
  assertthat::assert_that(!missing(d), msg = "Input d is missing")
  assertthat::assert_that(!missing(cols), msg = "Input cols is missing")
  assertthat::assert_that(is.data.frame(d), is.character(cols))
  
  col_check <- purrr::discard(cols, ~ .x %in% colnames(d))
  if(length(col_check) > 0){
    msg <- stringr::str_interp("${{paste(col_check, collapse = ', ')}} column(s) not available in the data frame")
    stop(msg)
  }
}
jennguyen1/scriptR documentation built on Aug. 6, 2018, 6:38 p.m.