Skip to content

Commit 8ca05e0

Browse files
authored
Change leading characters in label_date_short() (#456)
1 parent 16036b0 commit 8ca05e0

File tree

4 files changed

+33
-4
lines changed

4 files changed

+33
-4
lines changed

NEWS.md

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# scales (development version)
22

3+
* New `label_date_short(leading)` argument to replace leading zeroes (#442)
34
* `breaks_pretty()` will return the input limit when it has no range (#446)
45
* `transform_exp()` now has more sensible breaks, available in `breaks_exp()`
56
(@teunbrand, #405).

R/label-date.R

+15-3
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
#' uses the current locale. Setting this argument requires stringi, and you
2323
#' can see a complete list of supported locales with
2424
#' [stringi::stri_locale_list()].
25+
#' @param leading A string to replace leading zeroes with. Can be `""` to
26+
#' disable leading characters or `"\u2007"` for figure-spaces.
2527
#' @export
2628
#' @examples
2729
#' date_range <- function(start, days) {
@@ -53,8 +55,9 @@ label_date <- function(format = "%Y-%m-%d", tz = "UTC", locale = NULL) {
5355
#' @export
5456
#' @rdname label_date
5557
#' @param sep Separator to use when combining date formats into a single string.
56-
label_date_short <- function(format = c("%Y", "%b", "%d", "%H:%M"), sep = "\n") {
57-
force_all(format, sep)
58+
label_date_short <- function(format = c("%Y", "%b", "%d", "%H:%M"), sep = "\n",
59+
leading = "0") {
60+
force_all(format, sep, leading)
5861

5962
function(x) {
6063
dt <- unclass(as.POSIXlt(x))
@@ -90,7 +93,16 @@ label_date_short <- function(format = c("%Y", "%b", "%d", "%H:%M"), sep = "\n")
9093
)
9194

9295
format <- apply(for_mat, 1, function(x) paste(rev(x[!is.na(x)]), collapse = sep))
93-
format(x, format)
96+
x <- format(x, format)
97+
98+
if (isTRUE(leading == "0")) {
99+
return(x)
100+
}
101+
102+
# Replace leading 0s with `leading` character
103+
x <- gsub("^0", leading, x)
104+
x <- gsub(paste0(sep, "0"), paste0(sep, leading), x, fixed = TRUE)
105+
x
94106
}
95107
}
96108

man/label_date.Rd

+8-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/testthat/test-label-date.R

+9
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ test_that("can set locale", {
2424
expect_equal(time_format("%B", locale = "fr")(x), "janvier")
2525
})
2626

27+
test_that("label_date_short can replace leading zeroes", {
28+
x <- seq(as.Date("2024-01-01"), as.Date("2025-01-01"), by = "1 month")
29+
labels <- label_date_short(
30+
format = c("%Y", "%m", "%d"),
31+
sep = "-", leading = "x"
32+
)(x)
33+
expect_equal(labels, c("x1-2024", paste0("x", 2:9), c(10:12), "x1-2025"))
34+
})
35+
2736
test_that("date_short doesn't change unexpectedly", {
2837
expect_snapshot({
2938
dformat <- label_date_short()

0 commit comments

Comments
 (0)