I\'ve got a data frame with the following data:
>PRICE
DATE CLOSE
1 20070103 54.700
2 20070104 54.770
3 20070105 55.120
4 20070108 5
This answer based on @Joshua_Ulrich's answer creates a time series from the built-in airquality
dataset containing "Daily air quality measurements in New York, May to September 1973".
> head(airquality,3)
Ozone Solar.R Wind Temp Month Day
1 41 190 7.4 67 5 1
2 36 118 8.0 72 5 2
3 12 149 12.6 74 5 3
Convert Month and Day to a vector of class "Date"
airqualitydate = as.Date(sprintf("1973%02.0f%02.0f", airquality$Month, airquality$Day),
format="%Y%m%d")
Create the time series object
ts_airquality <- xts(airquality, airqualitydate)
head(ts_airquality, 3)
Ozone Solar.R Wind Temp Month Day
1973-05-01 41 190 7.4 67 5 1
1973-05-02 36 118 8.0 72 5 2
1973-05-03 12 149 12.6 74 5 3
Plot to illustrate the different output of the plot.xts() function. (compare to plot(airquality)
)
plot(ts_airquality$Ozone, main="Ozone (ppb)")
lines(ts_airquality$Temp, on=NA, main="Temperature (degrees F)")
Note, the base R ts()
method is mostly suited for quarterly or yearly data.
As explained in an answer to "starting a daily time series in R":
"Time Series Object does not work well with creating daily time series. I will suggest you use the zoo library."
In particular the xts
package is an extension to zoo
.