-3

One of the columns in my data frame is a character which has the following format (an example):

2013-02-05 08:00:00

Some of the rows are NULL in this column. I want to change the class to date format but I am getting NA for all rows.

Could you please tell me what should I do to make it work?

  • What happens if you type as.Date("2013-02-05 08:00:00") ? – Nikos Nov 25 '14 at 23:27
  • `as.Date(2013-02-05 08:00:00)` returns `2013-02-05` of class date. – DatamineR Nov 25 '14 at 23:28
  • Install the `lubridate` package and try `library(lubridate); ymd_hms()` on the column you want to convert. – eipi10 Nov 25 '14 at 23:32
  • If you want to keep the time, try `as.POSIXct("2013-02-05 08:00:00")` (assuming the time is in your local time zone). By some rows are "NULL" do you mean "NA"? You can't store a NULL in an atomic vector. Can you please edit your question to include a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – MrFlick Nov 25 '14 at 23:33
  • Actually, when I type as.Date(column name, format="%Y-%m-%d %h-%m-%s"), it gives me NA. – Gholam Mirzaee Nov 25 '14 at 23:34
  • Please (1) share some of your data, (2) in a reproducible way, (3) in your question. The best way would be to post `dput(your_data$your_date_column)`, though `str(your_data$your_date_column)` would also work. If your data is larger than 20 rows or so, only post the first 20 rows. – Gregor Thomas Nov 26 '14 at 00:39

2 Answers2

0

You should install Hadley Wickham's lubridate package, and use:

> ymd_hms("2013-02-05 08:00:00")

The package includes many other functions that'll help you (safely) manipulate datetime and interval objects.

mmuurr
  • 1,310
  • 1
  • 11
  • 21
  • When I do this: Pact$CDT <- as.POSIXct(Pact$CDT) (assume that Pact is my data table and CDT is the column), I am getting the following error: character string is not in a standard unambiguous format. – Gholam Mirzaee Nov 25 '14 at 23:45
0

Based on your comment, assuming your data frame is DF, and your date column (as character) DATE.STR, I would do the following:

DF$DATE=as.Date(DF$DATE.STR)

Of course, using lubridate would give you more options, but I think you can use base R for this.

Nikos
  • 3,267
  • 1
  • 25
  • 32