Need to convert char type column to date type

520 Views Asked by At

I have a data.table with a column named 'Date' and type char and it looks like below. I need to convert this to date type column so that i can perform date operations.

Date
"10/11/2018"
"13/11/2013"
"22/11/2011"
"--"
"--"
"10/11/2018"

I tried this, but doesn't work

MyTable$Date <- as.POXISlt(MyTable$Date)
1

There are 1 best solutions below

0
On

Welcome to SO!

Using data.table I'd suggest the following:

library(data.table)

MyTable <- data.table(Date = c(
  "10/11/2018",
  "13/11/2013",
  "22/11/2011",
  "--",
  "--",
  "10/11/2018"
))

MyTable[, posixDate := as.POSIXct(Date, format = "%d/%m/%Y")]

enter image description here

If you need to get rid of the NA rows use: na.omit(MyTable)