Constructing a flexible parameter checker

Hello!

Out of curiosity, I have been trying to build a check_params() function that makes sure the function parameters have no NULL values and returns a nice message. Something like this:

library(magrittr)

check_params <- function(a = NULL, b = NULL, c = NULL) {
  check_list <- list(
    a = a,
    b = b,
    c = c
  )

  missing_paramas <- check_list %>%
    purrr::keep(is.null) %>%
    names() %>%
    glue::glue_collapse(sep = ", ", last = " and ")

  if (length(missing_paramas) != 0) {
    stop(glue::glue("{missing_paramas} are required parameter(s)."))
  }
}

check_params()
#> Error in check_params(): a, b and c are required parameter(s).

Created on 2019-12-18 by the reprex package (v0.3.0)

What I am trying to do is not set the a, b, or c. I would like to just put this check_parmas() function at the top of my other functions that will look at the parameters of the function being called and check none are null. Is this possible? I feel like rlang has the tools I need to accomplish this, but I have not have had a lot of success. I want to grab the params of the parent function and check them that way.

Thank you for any guidance and help! :grin:

Kyle

Hi @KoderKow. Interesting. I give out my code but not elegant.

library(tidyverse)

check_params <- function() {
  args <- as.list(sys.calls()[[1]])
  argNames <- names(formals(fun = sys.function(sys.parent()), envir = parent.frame()))
  check_list <- map(setNames(argNames, argNames), ~{args[[.x]]})
  
  missing_paramas <- check_list %>%
    purrr::keep(is.null) %>%
    names() %>%
    glue::glue_collapse(sep = ", ", last = " and ")

  if (length(missing_paramas) != 0) {
    stop(glue::glue("{missing_paramas} are required parameter(s)."))
  }
}

test <- function(a, b, c) {
  check_params()
}

Created on 2019-12-19 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.