Search code examples
rtime-seriesrscript

R creating timeseries with existing dates from file


I'm trying to create a time series plot using R where obtain the dates from a REST request and then I want to group and count the date occurrences on a one week interval. I followed the examples of ts() in R and tried plots, which worked great. But I couldn't find any examples that shows how to create date aggregation based on existing data. Can someone point me in the proper direction?

This is a sample of my parsed REST data:

REST Response excerpt ....

"2014-01-16T14:51:50.000-0800"
"2014-01-14T15:42:55.000-0800"
"2014-01-13T17:29:08.000-0800"
"2014-01-13T16:19:31.000-0800"
"2013-12-16T16:56:39.000-0800"
"2014-02-28T08:11:54.000-0800"
"2014-02-28T08:11:28.000-0800"
"2014-02-28T08:07:02.000-0800"
"2014-02-28T08:06:36.000-0800"
....

Sincerely, code B.


Solution

  • You can define the date with "as.Date" and then create a time series with "xts", as it allows merging by any period of time.

    library(xts)
    REST$date <- as.Date(REST$date, format="%Y-%m-%d")
    REST$variable <- seq(0,2.4,by=.3)
    
    ts <- xts(REST[,"variable"], order.by=REST[,"date"])
    
    > to.monthly(ts)
             ts.Open ts.High ts.Low ts.Close
    Dec 2013     1.2     1.2    1.2      1.2
    Xan 2014     0.6     0.9    0.0      0.0
    Feb 2014     1.5     2.4    1.5      2.4
    
    > to.weekly(ts)
                ts.Open ts.High ts.Low ts.Close
     2013-12-16     1.2     1.2    1.2      1.2
     2014-01-16     0.6     0.9    0.0      0.0
     2014-02-28     1.5     2.4    1.5      2.4
    

    Not sure if this is what you needed. Is it?