-3

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)
Henrik
  • 65,555
  • 14
  • 143
  • 159
Yuvaraj
  • 1
  • 1
  • 1
  • use lubridate::dmy(Date), you need to install lubridate library – Hunaidkhan Nov 23 '18 at 11:19
  • 3
    lubridate isn't required, but is nice to use. Alternative is `as.Date("01/11/2018", "%d/%m/%Y")`. See https://www.statmethods.net/input/dates.html – Jonny Phelps Nov 23 '18 at 11:24
  • 1
    Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Nov 23 '18 at 11:29
  • @JonnyPhelps - I am getting this error as "character string is not in a standard unambiguous format" for as.Date(MyTable$Date) – Yuvaraj Nov 23 '18 at 12:08

1 Answers1

0

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)

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78