1

My sample dataset

data = c("2-2021", "8-2020", "11-2020", "11-2020", "7-2021", "12-2020", 
         "2-2021", "5-2021", "11-2020", "11-2020")

I require to add a leading zero to the month where applies.

Running this will throw all NA's

as.Date(data,format="%m-%Y")

So the desired output becomes

c("02-2021", "08-2020", "11-2020", "11-2020", "07-2021", "12-2020", 
         "02-2021", "05-2021", "11-2020", "11-2020")
Andres Mora
  • 1,040
  • 8
  • 16

3 Answers3

4

We can use truncated with myd from lubridate

library(lubridate)
myd(data, truncated = 2)

-output

[1] "2021-02-01" "2020-08-01" "2020-11-01" "2020-11-01" "2021-07-01" "2020-12-01" "2021-02-01" "2021-05-01" "2020-11-01" "2020-11-01"

The NAs in as.Date is not related to leading zeros, but the absence of day as a Date requires day, month and year part i.e. if we append the day part, it works

as.Date(paste0('1-', data), format = '%d-%m-%Y')
 [1] "2021-02-01" "2020-08-01" "2020-11-01" "2020-11-01" "2021-07-01" "2020-12-01" "2021-02-01" "2021-05-01" "2020-11-01" "2020-11-01"
akrun
  • 874,273
  • 37
  • 540
  • 662
3

Base R:

paste0(strrep("0", 7 - nchar(data)), data)
#  [1] "02-2021" "08-2020" "11-2020" "11-2020" "07-2021" "12-2020" "02-2021" "05-2021" "11-2020" "11-2020"

If you need it in Date class and this is just an interim step, then you could instead do

as.Date(paste0("1-", data), format = "%d-%m-%Y")
#  [1] "2021-02-01" "2020-08-01" "2020-11-01" "2020-11-01" "2021-07-01" "2020-12-01" "2021-02-01" "2021-05-01" "2020-11-01" "2020-11-01"

(which does not care if the month has a leading 0 or not). (Looks like akrun beat me to this second step by a few seconds :-)

r2evans
  • 141,215
  • 6
  • 77
  • 149
1

This is also a way we colud do it:

  1. create a datetime format with parse_date_time and format it to month and year. which will automatically add leading zeros:
library(lubridate)

format(parse_date_time(data, "my"), "%m-%Y")
 [1] "02-2021" "08-2020" "11-2020" "11-2020"
 [5] "07-2021" "12-2020" "02-2021" "05-2021"
 [9] "11-2020" "11-2020"
TarJae
  • 72,363
  • 6
  • 19
  • 66