Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting the data in year month day hour and minutes to date in R

Tags:

r

I am trying to convert the date as factor to date using “as.date” function in R. I have the date in the following format

2008-01-01 02:30

I tried to use the following command :

as.Date(mydata$Date, format="%y-%m-%d  %h:%mm")

Can somebody help me with this ? I was able to convert the format with no hour but getting difficulty with hour included.

Thank you.

like image 421
Jd Baba Avatar asked Feb 19 '13 18:02

Jd Baba


People also ask

How do I convert a variable to a date 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.

What is POSIXct format in R?

POSIXct stores date and time in seconds with the number of seconds beginning at 1 January 1970. Negative numbers are used to store dates prior to 1970. Thus, the POSIXct format stores each date and time a single value in units of seconds. Storing the data this way, optimizes use in data.

How do I change time format in R?

To convert characters to time objects in R, use the strptime() function. To convert time objects to characters in R, use the strftime() function.


1 Answers

Your format string is incorrect :

R> strptime("2008-01-01 02:30", format="%Y-%m-%d  %H:%M")
# [1] "2008-01-01 02:30:00"

See ?strptime for the detailed values you can use to define a format.

Also note that as your string is in a standard format, you can also use directly as.POSIXlt :

R> as.POSIXlt("2008-01-01 02:30")
# [1] "2008-01-01 02:30:00"
like image 67
juba Avatar answered Sep 24 '22 23:09

juba