Usually for plotting or reports one needs to print the range of a datasets. This function prints a nice range of dates or numbers easily

prettify_range(x, y = NULL, sep = "–")

Arguments

x, y

column with the number/dates/years/etc. If y is NULL the range is determined by the minimum and maximum value in x. If y is not NULL the beginning of the range is determined by the minimum of x and the end of the range by the maximum of y

sep

separator between the range

Value

a character with the range

Examples


# Range of a numeric vector
prettify_range(1:100)
#> [1] "1–100"
# Changing the default separator
prettify_range(1:100, sep = " to ")
#> [1] "1 to 100"
# Range using two numbers
prettify_range(1, 100)
#> [1] "1–100"
# When two vectors are provided the minimum of the first and the maximum of the
# second is returned
tibble::tibble(period_start = 2010:2020,
               period_end = 2020:2030) %>%
  dplyr::mutate(pretty_range = prettify_range(period_start, period_end))
#> # A tibble: 11 × 3
#>    period_start period_end pretty_range
#>           <int>      <int> <chr>       
#>  1         2010       2020 2010–2030   
#>  2         2011       2021 2010–2030   
#>  3         2012       2022 2010–2030   
#>  4         2013       2023 2010–2030   
#>  5         2014       2024 2010–2030   
#>  6         2015       2025 2010–2030   
#>  7         2016       2026 2010–2030   
#>  8         2017       2027 2010–2030   
#>  9         2018       2028 2010–2030   
#> 10         2019       2029 2010–2030   
#> 11         2020       2030 2010–2030   
# Also work with dates
seq(Sys.Date(), Sys.Date() + 100, length.out = 100) %>%
  prettify_range(sep = " and ") %>%
  paste("between", .)
#> [1] "between 2026-09-01 and 2026-12-10"