Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Last active December 15, 2023 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-dray/65ec5de010d89edd3ac2185788f35aa2 to your computer and use it in GitHub Desktop.
Save matt-dray/65ec5de010d89edd3ac2185788f35aa2 to your computer and use it in GitHub Desktop.
A base-R-only function to check argument inputs to another function, using dots to assess several of those inputs at once
test_fn <- function(x = 1L, y = "x", z = 1.1) {
.check_type(x, y, z, type = "numeric")
cat("success")
}
.check_type <- function(..., type = "numeric") {
args <- list(...)
arg_names <- as.character(substitute(...()))
names(args) <- arg_names
type_list_lgl <- lapply(args, function(arg) inherits(arg, type))
if (length(failing_args_names) > 0) {
failing_args <- args[names(args) %in% failing_args_names]
failing_args_classes <- lapply(failing_args, class)
pasted_names <- .make_listed_sentence(names(failing_args_classes))
pasted_classes <- .make_listed_sentence(failing_args_classes)
stop(
"The input to argument ", pasted_names, " must be of type ", type, ". " ,
"You provided input of type ", pasted_classes, ".",
call. = FALSE
)
}
}
.make_listed_sentence <- function(...) {
values <- c(...)
if (length(values) == 1) {
return(values)
}
if (length(values) > 1) {
last_value <- values[length(values)]
first_values <- setdiff(values, last_value)
paste(paste(first_values, collapse = ", "), "and", last_value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment