Time-efficient way to convert column to as.Date column

Viewed 45

What is the most time-efficient way to convert "Transaction" column into format as.Date() without the transaction time? Thanks!

ID <- c(10,27,35)
Transaction <- c("15-JAN-20 12.00.00","10-MAR-19 13.00.00","01-JAN-20 13.30.00")

df <- data.frame(ID, Transaction)

2 Answers

as.Date will ignore junk at the end. No packages are used.

transform(df, date = as.Date(Transaction, "%d-%b-%y"))

giving:

  ID        Transaction       date
1 10 15-JAN-20 12.00.00 2020-01-15
2 27 10-MAR-19 13.00.00 2019-03-10
3 35 01-JAN-20 13.30.00 2020-01-01

This solution also works with lubridate package:

library(dplyr)
library(lubridate)

df %>%
  mutate(date = date(dmy_hms(Transaction)))

  ID        Transaction       date
1 10 15-JAN-20 12.00.00 2020-01-15
2 27 10-MAR-19 13.00.00 2019-03-10
3 35 01-JAN-20 13.30.00 2020-01-01

Related