High Low
High Low

Reputation: 67

Standardizing the date format using R

I am having trouble standardizing the Date format to be dd-mm-YYYY, This is my current code

Dataset

         date
1  23/07/2020
2 22-Jul-2020

Current Output

df$date<-as.Date(df$date)
df$date = format(df$date, "%d-%b-%Y")

         date
1 20-Jul-0022
2        <NA>

Desired Output

         date
1 23-Jul-2020
2 22-Jul-2020

Upvotes: 0

Views: 186

Answers (2)

Mike V
Mike V

Reputation: 1364

You can try this way

library(lubridate)
df$date <- dmy(df$date)
df$date <- format(df$date, format = "%d-%b-%Y")

#         date
# 1 23-Jul-2020
# 2 22-Jul-2020

Data

 df <- read.table(text = "date
    1  23/07/2020
    2 22-Jul-2020", header = TRUE)

Upvotes: 1

stlba
stlba

Reputation: 767

I've saved your example data set as a dataframe named df. I used group_by from dplyr to all each date to be converted separately to the correct format.

library(tidyverse)

df  %>% 
     group_by(date) %>% 
     mutate(date = as.Date(date, tryFormats = c("%d-%b-%Y", "%d/%m/%Y"))) %>% 
     mutate(date = format(date, "%d-%b-%Y"))

Upvotes: 0

Related Questions