这为整数和小数范围提供了通用解决方案(无需手动指定增量):
library(stringr)
pretty_cuts <- function(cut_str) {
# so we know when to not do something
first_val <- as.numeric(str_extract_all(cut_str[1], "[[:digit:]\\.]+")[[1]][1])
last_val <- as.numeric(str_extract_all(cut_str[length(cut_str)], "[[:digit:]\\.]+")[[1]][2])
sapply(seq_along(cut_str), function(i) {
# get cut range
x <- str_extract_all(cut_str[i], "[[:digit:]\\.]+")[[1]]
# see if a double vs an int & get # of places if decimal so
# we know how much to inc/dec
inc_dec <- 1
if (str_detect(x[1], "\\.")) {
x <- as.numeric(x)
inc_dec <- 10^(-match(TRUE, round(x[1], 1:20) == x[1]))
} else {
x <- as.numeric(x)
}
# if not the edge cases inc & dec
if (x[1] != first_val) { x[1] <- x[1] + inc_dec }
if (x[2] != last_val) { x[2] <- x[2] - inc_dec }
sprintf("%s - %s", as.character(x[1]), as.character(x[2]))
})
}
dummy <- data.frame(important_variable=seq(1:1000))
dummy$cuts <- cut2(dummy$important_variable, g = 4)
a <- pretty_cuts(dummy$cuts)
unique(dummy$cuts)
## [1] [ 1, 251) [251, 501) [501, 751) [751,1000]
## Levels: [ 1, 251) [251, 501) [501, 751) [751,1000]
unique(a)
## [1] "1 - 250" "252 - 500" "502 - 750" "752 - 1000"
x2 <- runif(100, 5.0, 7.5)
b <- pretty_cuts(cut2(x2, g=4))
unique(cut2(x2, g=4))
## [1] [5.54,6.28) [6.28,6.97) [6.97,7.50] [5.02,5.54)
## Levels: [5.02,5.54) [5.54,6.28) [6.28,6.97) [6.97,7.50]
unique(b)
## [1] "5.54 - 6.27" "6.29 - 6.97" "6.98 - 7.49" "5.03 - 5.53"