R-Create a single date from multiple columns

I hope I have a simple question for all of you, but working with dates in R was difficult for me.

I have time series data that look 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 several columns, and then plot the data by date. My hopeless simplified 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 that this will not work, but I hope that he can understand the essence of what I want to accomplish. Any ideas on how to do this?

Thanks in advance!

+7
source share
1 answer

You need 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 the 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 for example and had only one argument, which was numbered. But with your data in the mydf variable, let's say you could do

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

and you have to be tuned and ready to build. You can also assign the mytimes column mytimes original data.frame .

+11
source

All Articles