Skip to content

Instantly share code, notes, and snippets.

@joelnitta
Created October 5, 2021 03:45
Show Gist options
  • Save joelnitta/e876759b3b9870c11301ce7a8b9c822c to your computer and use it in GitHub Desktop.
Save joelnitta/e876759b3b9870c11301ce7a8b9c822c to your computer and use it in GitHub Desktop.
Function to check names of input to a function
# This function can be called inside of other functions to check
# if the names of the input match the names of the arguments
check_args <- function(call_match) {
call_names <- as.character(call_match)
arg_names <- names(as.list(call_match))
stopifnot(
"Names of input must match names of arguments" = isTRUE(all.equal(call_names[-1], arg_names[-1]))
)
}
# For example, define a "strict sum" function
strict_sum <- function(a, b, c) {
# check that the input names match the arguments
check_args(match.call())
# if they do, calculate the sum
sum(c(a, b, c))
}
# Try it out
a <- 1
b <- 2
c <- 3
# This works, because the names of the input (the input objects themselves)
# match the names of the function arguments
strict_sum(a,b,c)
# But these will fail
strict_sum(a,b,3)
strict_sum(b,a,c) # etc...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment