Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Created June 15, 2020 00: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 mrdwab/e48cf0c22d038e00237b57bf7cc1211e to your computer and use it in GitHub Desktop.
Save mrdwab/e48cf0c22d038e00237b57bf7cc1211e to your computer and use it in GitHub Desktop.
set.seed(1)
data_pos <- sample(0:50, 100, TRUE)
data_neg <- sample(-50:-1, 100, TRUE)
data_pos_neg <- c(0, sample(-50:50, 100, TRUE))
x <- runif(50, -5, 5)
grouped_stem <- function(invec, n = 2) {
if (!all(as.numeric(invec) == as.integer(invec))) stop("This function only works with integers")
invec <- sort(invec)
negative <- if (any(invec < 0)) TRUE else FALSE
positive <- if (any(invec >= 0)) TRUE else FALSE
type <- c("positive", "negative")[c(positive, negative)]
type <- if (length(type) == 2) "both" else type
out <- switch(type,
negative = gsn(invec[invec < 0], n),
positive = gsp(invec[invec >= 0], n),
both = c(gsn(invec[invec < 0], n),
gsp(invec[invec >= 0], n)))
class(out) <- c("grp_stem", class(out))
out
}
gsn <- function(negs, n = 2) {
cuts <- seq(((min(negs) %/% 10)-1) * 10, 0)
labs <- sub("(.*).$", "\\1", cuts+1)
labs <- replace(labs, labs == "-" | !nzchar(labs), "-0")
temp <- split(negs, cut(negs, cuts, labs[-length(labs)], right = TRUE))
temp <- relist(sub(".*(.)$", "\\1", unlist(temp, use.names = FALSE)), temp)
combined <- vapply(temp, function(y) sprintf("%s*", paste(y, collapse = "")), character(1L))
splits <- split(combined, ((seq_along(combined)-1) %/% n))
stems <- vapply(splits, function(x) {
paste(names(x)[1], names(x)[length(x)], sep = " to ")
}, character(1L))
leaves <- vapply(splits, function(x) {
sub("[*]$", "", paste(x, sep = "", collapse = ""))
}, character(1L))
setNames(as.list(leaves), stems)
}
gsp <- function(poss, n = 2) {
cuts <- seq((min(poss) %/% 10) * 10, round(max(poss)+10, -(nchar(max(poss))-1)), 10)
labs <- sub("(.*).$", "\\1", cuts)
labs <- replace(labs, !nzchar(labs), "0")
temp <- split(poss, cut(poss, cuts, labs[-length(labs)], right = FALSE))
temp <- relist(sub(".*(.)$", "\\1", unlist(temp, use.names = FALSE)), temp)
combined <- vapply(temp, function(y) sprintf("%s*", paste(y, collapse = "")), character(1L))
splits <- split(combined, ((seq_along(combined)-1) %/% n))
stems <- vapply(splits, function(x) {
paste(names(x)[1], names(x)[length(x)], sep = " to ")
}, character(1L))
leaves <- vapply(splits, function(x) {
sub("[*]$", "", paste(x, sep = "", collapse = ""))
}, character(1L))
setNames(as.list(leaves), stems)
}
print.grp_stem <- function(x, ...) {
cat(sprintf(sprintf("%%%ss | %%s", max(nchar(names(x)))+2),
names(x), unlist(x, use.names = FALSE)), sep = "\n")
}
grouped_stem(data_neg, 2)
grouped_stem(data_pos, 2)
grouped_stem(data_pos_neg, 3)
grouped_stem(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment