Search code examples
rtimetime-seriesforecast

Can I specify the dates and times of a time series in R?


I have a dataset that contains times and dates in the first column, and the stock prices in the second column.

I used the following format.

      Time              Price
2015-02-01 10:00         50

I want to turn this into a time series object. I tried ts(data) function, but when I plot the data I cannot observe the dates in the x-axis. Also I tried ts(data, start=) function. Because I have some hours with missing prices, and those hours are not included in my data set, if I set start date and frequency, my plot will be misleading.

Here is the sample data that I have. It is called df.

           time         price    

1   2013-05-01 00:00:00 124.30
2   2013-05-01 01:00:00 98.99
3   2013-05-01 02:00:00 64.00
4   2013-05-01 03:00:00 64.00

This is the code that I used

Time1 <- ts(df) 
autoplot(Time1)

Also tried this,

Time1 <- zoo(Time_series_data[,2], order.by = Time_series_data[,1])
Time_n <- ts(Time1)
autoplot(Time1)

However, when I plot the graph with autoplot(Time1) the x-axis doesn't show the times that I specified but numbers from 0 to 4. I want to have plot of a ts object that includes the date columns in the x-axis and values in Y

Is there any way to convert it to a time series object in R. Thanks.


Solution

  • Try the following:

    Create some data using the nifty tribble function from the tibble package.

    library(tibble)
    df <- tribble(~time,      ~price,
       "2013-05-01 00:00:00", 124.30,
       "2013-05-01 01:00:00", 98.99,
       "2013-05-01 02:00:00", 64.00,
       "2013-05-01 03:00:00", 64.00)
    

    The time column is a character class and cannot be plotted in the usual way. So convert it using as.Posixct. I'll use the dplyr package here but that's optional.

    library(dplyr)
    
    df <- df %>%
      mutate(time=as.POSIXct(time))
    

    Next, convert the data to a time series object. This requires the xts package, although I'm sure there are other options including zoo.

    library(xts)
    df.ts <- xts(df[, -1], order.by=df$time)
    

    Now you can visualise the data.

    plot(df.ts)  # This should call the `plot.xts` method
    

    And if you prefer ggplot2.

    library(ggplot2)
    autoplot(df.ts)