Skip to content

Instantly share code, notes, and snippets.

@jmbarbone
Created October 5, 2023 16:51
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 jmbarbone/dab69e1ffea0fab76e79f681410fe431 to your computer and use it in GitHub Desktop.
Save jmbarbone/dab69e1ffea0fab76e79f681410fe431 to your computer and use it in GitHub Desktop.
Some enhancements for `dput()` with integer vectors
dput_int_string <- function(x) {
x <- sort(unique(as.integer(x)))
d <- diff(x) == 1
if (length(x) == 1 || all(d)) {
return(utils::capture.output(dput(x)))
}
d[!d] <- NA
d <- c(d, NA)
len <- rle(d)$lengths
end <- cumsum(len)[len > 1] + 1
start <- end - len[len > 1]
singles <- setdiff(seq_along(x), unlist(mapply(seq.int, start, end)))
ind <- sort(c(singles, start))
res <- paste0((x[ind]), "L")
res[match(start, ind)] <- paste(x[start], x[end], sep = ":")
paste0("c(", paste0(res, collapse = ", "), ")")
}
stopifnot(
dput_int_string(c(0, 2, 6:8, 10, 12:20)) == "c(0L, 2L, 6:8, 10L, 12:20)"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment