0

I have the month in the usual format (2, 3, 4, and so on) but I wish to always have it in a 2 digit format so this would become (02, 03, 10, 11, 12).

Currently what I have as just;

themonth = month(Sys.Date())

I've tried putting as.numeric around this but out of ideas pretty quickly on this one

zx8754
  • 52,746
  • 12
  • 114
  • 209
Joe
  • 795
  • 1
  • 11

3 Answers3

4
format(Sys.Date(), "%m")
# [1] "02"
Merijn van Tilborg
  • 5,452
  • 1
  • 7
  • 22
2

You can use sprintf

sprintf('%02d', lubridate::month(Sys.Date()))
#> [1] "02"

With a double digit month, there is no leading 0.

sprintf('%02d', lubridate::month(as.Date('2023-10-01')))
[1] "10"
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
1

You may try using ifelse

x <- lubridate::month(Sys.Date())
ifelse(nchar(x) == 1, paste0(0, x), x)
[1] "02"
Park
  • 14,771
  • 6
  • 10
  • 29