Skip to content

Instantly share code, notes, and snippets.

@ATpoint
Created October 18, 2023 09:55
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 ATpoint/89343ffa2bee975e2eab5982119ac413 to your computer and use it in GitHub Desktop.
Save ATpoint/89343ffa2bee975e2eab5982119ac413 to your computer and use it in GitHub Desktop.
#' Create unique combinations
#'
#' To a given vector of numeric values add or subtract a constant value,
#' and return all possible combinations of that as a matrix
#'
#' @param values a vector with numeri values
#' @param change_value a numeric value too add or subtract
#'
#' @details
#' There are 2^length(values) possible combinations
#'
#' @examples
#' generate_combinations(c(1,2,3), .1)
#'
generate_combinations <- function(values, change_value = 0.1) {
if(!is.numeric(values)) stop("values must be a numeric vector")
if(!is.numeric(change_value)) stop("change_value must be numeric")
all_changes <- c(change_value, -change_value)
combinations <- expand.grid(rep(list(all_changes), length(values)))
vectorized <- as.numeric(t(combinations)) + values
final <- matrix(vectorized, byrow=TRUE, ncol=length(values))
return(final)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment