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)
Edit on 2023-03-02:
After {tidyverse} 2.0.0, {lubridate} is attached after attaching {tidyverse}, so there is no need to attach {lubridate} now:
library(tidyverse)
dt <- "1998-09-02"
str_glue("{year(dt)}, {month(dt)}, {day(dt)}")
#> 1998, 9, 2
Created on 2023-03-02 with reprex v2.0.2
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)
%D
or whatever that removes leading zeros. – Samarskite