Created
October 5, 2023 16:51
-
-
Save jmbarbone/dab69e1ffea0fab76e79f681410fe431 to your computer and use it in GitHub Desktop.
Some enhancements for `dput()` with integer vectors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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