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?
>Solution :
date_cols
should be defined asc("Date1", "Date2")
- Since
date1
anddate2
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]