Search code examples
rdatedata-manipulation

date format without leading zeros - R


I have dates in a character vector and I'm looking for a way to transform it to date format with as.Date():

vector <- c("15/1/2019", "5/5/2019")

However, as.Date(vector, format="%d/%m/%Y") receives as input characters with zeros leading. And I have found plenty of solutions for:

Input: "15/01/2019"
Output: "15/1/2019"

However, I need exactly the opposite to make as.Date() to work:

Input: "15/1/2019" "5/5/2019"
Output: "15/01/2019" "05/05/2019"

Is there any specific formatting for format argument? Or I have to use a substr() solution?


Solution

  • We can use strftime.

    strftime(as.Date(inp, format="%d/%m/%Y"), format="%d/%m/%Y")
    # [1] "15/01/2019" "05/05/2019"
    

    Data

    inp <- c("15/1/2019", "5/5/2019")