Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting column to datetime in R

The date in my dataset is like this: 20130501000000 and I'm trying to convert this to a better datetime format in R

data1$date <- as.Date(data1$date, format = "%Y-%m-%s-%h-%m-%s")

However, I get an error for needing an origin. After I put the very first cell under date in as origin, it converts every cell under date to N/A. Is this right or should I try as.POSIXct()?

like image 452
ajax2000 Avatar asked Jan 08 '17 19:01

ajax2000


People also ask

How do I convert a character column to a date column in R?

You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.

How do you change a column from character to time in R?

We can convert the character to timestamp by using strptime() method. strptime() function in R Language is used to parse the given representation of date and time with the given template.

How do I create a date column in R?

To create a Date object from a simple character string in R, you can use the as. Date() function. The character string has to obey a format that can be defined using a set of symbols (the examples correspond to 13 January, 1982): %Y : 4-digit year (1982)


1 Answers

That is a somewhat degenerate format, but the anytime() and anydate() functions of the anytime package can help you, without requiring any explicit format strings:

R> anytime("20130501000000")       ## returns POSIXct
[1] "2013-05-01 CDT"
R> anydate("20130501000000")       ## returns Date
[1] "2013-05-01"
R> 

Not that we parse from character representation here -- parsing from numeric would be wrong as we use a conflicting heuristic to make sense of dates stored a numeric values.

So here your code would just become

data1$data <- anytime::anydate(data1$date)

provided data1$date is in character, else wrap one as.character() around it.

Lastly, if you actually want Datetime rather than Date (as per your title), don't use anydate() but anytime().

like image 111
Dirk Eddelbuettel Avatar answered Sep 21 '22 21:09

Dirk Eddelbuettel