Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

data.table lappy convert date from numeric yyyymmdd to date format

Given the following DT:

Date1 <- c(20210103, 20220805, 20191231)                       
Amount <- c(10,20,30)                     
Date2 <- c(20190101, 20180220, 20240930) 
dt_1 <- data.table(Date1, Amount, Date2) 
dt_1

I am trying to convert the numeric yyymmdd to date format:

date_cols <- c(Date1, Date2)
dt_1 <- dt_1[, (date_cols) := lapply(.SD, as.Date), .SDcols = date_cols]

can you help me to fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. date_cols should be defined as c("Date1", "Date2")
  2. Since date1 and date2 are numbers, change them to character first before converting them to date. Additionally, you need to supply the format the dates are present in your data.
library(data.table)

date_cols <- c("Date1", "Date2")

dt_1[, (date_cols) := lapply(.SD, \(x) as.Date(as.character(x), '%Y%m%d')), 
       .SDcols = date_cols]

#        Date1 Amount      Date2
#1: 2021-01-03     10 2019-01-01
#2: 2022-08-05     20 2018-02-20
#3: 2019-12-31     30 2024-09-30

Or you may also use lubridate::ymd which works without changing dates to characters and supplying the format explicitly.

dt_1[, (date_cols) := lapply(.SD, lubridate::ymd), .SDcols = date_cols]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading