Skip to content

Instantly share code, notes, and snippets.

@AdamSpannbauer
Created November 14, 2022 13:32
Show Gist options
  • Save AdamSpannbauer/0fd43776185e059882660f2f55b51141 to your computer and use it in GitHub Desktop.
Save AdamSpannbauer/0fd43776185e059882660f2f55b51141 to your computer and use it in GitHub Desktop.
Convert arules::discretize's factor levels to a more approachable format for non-technical audience
prettify_discretize_labs <- function(x, sep = " to ") {
all_labs <- levels(x)
split_labs <- strsplit(all_labs, ",")
old_options <- options(scipen = 999)
pretty_labs <- vapply(split_labs, function(el) {
num_chrs <- gsub("\\[|\\]|\\(|\\)", "", el)
nums <- as.numeric(num_chrs)
pretty_lab <- paste(nums[1], nums[2], sep = sep)
}, character(1))
options(scipen = old_options$scipen)
levels(x) <- pretty_labs
return(x)
}
# # Example usage:
#
# library(arules)
#
# set.seed(42)
#
# vals <- rnorm(100, mean = 5000, 10000)
# discretized <- discretize(vals)
#
# levels(discretized)
# # [1] "[-2.49e+04,1.93e+03)"
# # [2] "[1.93e+03,1.08e+04)"
# # [3] "[1.08e+04,2.79e+04]"
#
# discretized <- prettify_discretize_labs(discretized)
#
# levels(discretized)
# # [1] "-24900 to 1930"
# # [2] "1930 to 10800"
# # [3] "10800 to 27900"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment