Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R- Create a single date from multiple columns

Tags:

r

I hope I have a simple question for you all, but working with dates in R has been a difficulty for me

I have a time series data that looks like this

Month  Day  Year  Hour  Min  Sec Data
2       1    2012  1     0   0    56
2       1    2012  1     1   0    57
2       1    2012  1     2   0    52
2       1    2012  1     3   0    55
2       1    2012  1     4   0    57

My hope is to create a single date from the multiple columns and then plot the Data column by the date. My hopelessy oversimplified code would look like this:

Date1<-c(Month,Day,Year,Hour,Min,Sec)# For when hourly data is important
Date2<-c(Month,Day,Year) #For when daily data is important
as.Date(Date1)
as.Date(Date2)
plot(Data~ Date1)

I know it does not work, but I hope it can get the point across of what I am looking to accomplish. Any ideas on how one might go about doing this?

Thanks ahead of time!

like image 886
Vinterwoo Avatar asked Mar 21 '12 21:03

Vinterwoo


1 Answers

You want the ISOdatetime() function:

R> mytimes <- ISOdatetime(2012,1,2,1,2,c(3.123,3.456,3.789),tz="UTC")
R> mytimes
[1] "2012-01-02 01:02:03.122 UTC" "2012-01-02 01:02:03.456 UTC" 
[3] "2012-01-02 01:02:03.789 UTC"

And these are real POSIXct objects:

R> diff(mytimes)
Time differences in secs
[1] 0.333 0.333
attr(,"tzone")
[1] "UTC"
R> 

I made my life easier here for the example and had just one argument vectorised. But with your data in a variable mydf, say, you could do

mytimes <- with(mydf, ISOdatetime(Year, Month, Day, Hour, Min, Sec))

and you should be set and ready for plotting. You can also re-assign the mytimes column to the original data.frame.

like image 190
Dirk Eddelbuettel Avatar answered Nov 10 '22 20:11

Dirk Eddelbuettel