0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 17 '20 at 22:48
  • ts series are mostly used for monthly or quarterly or annual data. For daily data you can create a zoo or xts series using the respective packages. – G. Grothendieck Feb 17 '20 at 23:02
  • Convert your datetimes to POSIXct if you want to plot or manipulate it. You probably have character or factor data currently. – G. Grothendieck Feb 17 '20 at 23:05

1 Answers1

1

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)
Edward
  • 10,360
  • 2
  • 11
  • 26