Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Last active December 18, 2023 21:42
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/0301ede9802339a442d589ce9cfc5b91 to your computer and use it in GitHub Desktop.
Save matt-dray/0301ede9802339a442d589ce9cfc5b91 to your computer and use it in GitHub Desktop.
Checking pairs of vector inputs to an R function to see if the longer of each pair is a multiple of the shorter, emit a dynamic warning if so
pair_inputs <- function(...) {
args <- rlang::dots_list(..., .named = TRUE)
args_lengths <- lapply(args, length)
pairs <- combn(args_lengths, 2, simplify = FALSE)
failed <- lapply(pairs, function(x) max(unlist(x)) %% min(unlist(x)) != 0)
if (any(unlist(failed))) {
failed_i <- which(unlist(failed))
failed_pairs <- lapply(pairs[failed_i], unlist)
failed_pasted <- lapply(
failed_pairs,
function(x) {
x <- sort(x, decreasing = TRUE)
paste0(
"{.var ", names(x[1]), "} had length ", x[1],
" but ",
"{.var ", names(x[2]), "} had length ", x[2]
)
}
)
names(failed_pasted) <- rep("*", length(failed_pasted))
cli::cli_warn(
c(
i = "Longer object length is not a multiple of shorter object length.",
i = "Vectors were recycled with some values left over.",
i = "This occurred because:",
unlist(failed_pasted)
)
)
}
}
pair_inputs(x = 1:2, y = 7:1, z = 1:5, a = 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment