Formatting a date in R without leading zeros

Just remove the leading zeros at the end:

gsub(" 0", " ", format(as.Date("1998-09-02"), "%Y, %m, %d"))
## [1] "1998, 9, 2"

Use %e to obtain a leading space instead of a leading zero.


You can do this with a simple change to your strftime format string. However, it depends on your platform (Unix or Windows).

Unix

Insert a minus sign (-) before each term you'd like to remove leading zeros from:

format(as.Date("2020-06-02"), "%Y, %-m, %-d")
[1] "2020, 6, 2"

Windows

Insert a pound sign (#) before each desired term:

format(as.Date("2020-06-02"), "%Y, %#m, %#d")
[1] "2020, 6, 2"

I have discovered a workaround by using year(), month() and day() function of {lubridate} package. With the help of glue::glue(), it is easy to do it as following:

library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
library(glue)
dt <- "1998-09-02"
glue("{year(dt)}, {month(dt)}, {day(dt)}")
#> 1998, 9, 2

Created on 2021-04-19 by the reprex package (v2.0.0)

If {tidyverse} is used (suggested by @banbh), then str_glue() can be used:

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
dt <- "1998-09-02"
str_glue("{year(dt)}, {month(dt)}, {day(dt)}")
#> 1998, 9, 2

Created on 2021-04-19 by the reprex package (v2.0.0)