Home > OS >  change multiple dates formatting in R
change multiple dates formatting in R

Time:10-09

I'm trying to apply date formatting to existing dates columns in a dataset.

I tried using across function to change date format but with no luck. i don't want to create new column rather change the format in existing columns.

Example below,

doc_dt <- c('04/22/2021 00:00:00', '05/15/2021 00:00:00')
ship_dt <- c('04/24/2021 00:00:00', '05/18/2021 00:00:00')
qty <- c(10, 20)

df_dt <- data.frame(doc_dt,ship_dt, qty)

col_dt <- c('doc_dt','ship_dt')

format_dt <- df_dt %>%
mutate(
across(col_dt, ~ format(as.POSIXct(.x, format="%m/%d/%Y %H:%M:%S"),"%Y-%m-%d"))
)

CodePudding user response:

We could use as.Date directly from base R

library(dplyr)
result <- df_dt %>% 
    mutate(across(all_of(col_dt), ~ as.Date(doc_dt, "%m/%d/%Y %T")))
result
      doc_dt    ship_dt qty
1 2021-04-22 2021-04-22  10
2 2021-05-15 2021-05-15  20

CodePudding user response:

We could use mdy_hms from lubridate package directly:

library(dplyr)
library(lubridate)
df_dt %>% 
  mutate(across(contains("dt"),mdy_hms))
      doc_dt    ship_dt qty
1 2021-04-22 2021-04-24  10
2 2021-05-15 2021-05-18  20

CodePudding user response:

An alternative would be to use lubridate functions.

library(dplyr)
library(lubridate)

result <- df_dt %>% mutate(across(all_of(col_dt), ~ as.Date(mdy_hms(.))))
result

#      doc_dt    ship_dt qty
#1 2021-04-22 2021-04-24  10
#2 2021-05-15 2021-05-18  20

str(result)

#'data.frame':  2 obs. of  3 variables:
# $ doc_dt : Date, format: "2021-04-22" "2021-05-15"
# $ ship_dt: Date, format: "2021-04-24" "2021-05-18"
# $ qty    : num  10 20
  • Related