Last active
December 15, 2023 10:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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