<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/time-series-analysis-in-r-part-1-the-time-series-object/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datascienceplus.com/time-series-analysis-in-r-part-1-the-time-series-object/"> R Programming – DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Many of the methods used in time series analysis and forecasting have been around for quite some time but have taken a back seat to machine learning techniques in recent years. Nevertheless, time series analysis and forecasting are useful tools in any data scientist’s toolkit. Some recent time series-based competitions have recently appeared on kaggle, such as <a rel="nofollow" href="https://www.kaggle.com/c/web-traffic-time-series-forecasting" target="_blank">one hosted by Wikipedia</a> where competitors are asked to forecast web traffic to various pages of the site. As an economist, I have been working with time series data for many years; however, I was largely unfamiliar with (and a bit overwhelmed by) R’s functions and packages for working with them. From the base <code>ts</code> objects to a whole host of other packages like <code>xts</code>, <code>zoo</code>, <code>TTR</code>, <code>forecast</code>, <code>quantmod</code> and <code>tidyquant</code>, R has a large infrastructure supporting time series analysis. I decided to put together a guide for myself in Rmarkdown. I plan on sharing this as I go in a series of blog posts. In part 1, I’ll discuss the fundamental object in R – the <code>ts</code> object.</p>
<h2>The Time Series Object</h2>
<p>In order to begin working with time series data and forecasting in R, you must first acquaint yourself with R’s <code>ts</code> object. The <code>ts</code> object is a part of base R. Other packages such as <code>xts</code> and <code>zoo</code> provide other APIs for manipulating time series objects. I’ll cover those in a later part of this guide.</p>
<p>Here we create a vector of simulated data that could potentially represent some real-world time-based data generation process. It is simply a sequence from 1 to 100 scaled up by 10 to avoid negatives and with some random normal noise added to it. We can use R’s base <code>plot()</code> function to see what it looks like:</p>
<pre>set.seed(123)
t &lt;- seq(from = 1, to = 100, by = 1) + 10 + rnorm(100, sd = 7)
plot(t)</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsguide1.png?ssl=1" target="_blank"><img sizes="(max-width: 1344px) 100vw, 1344px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsguide1.png?w=450&ssl=1" alt="" class="wp-image-8403" data-recalc-dims="1"></a></p>
<p>This could potentially represent some time series, with time represented along the x-axis. However, it’s hard to tell. The x-axis is simply an index from 1 to 100 in this case.</p>
<p>A vector object such as <code>t</code> above can easily be converted to a time series object using the <code>ts()</code> function. The <code>ts()</code> function takes several arguments, the first of which, <code>x</code>, is the data itself. We can look at all of the arguments of <code>ts()</code> using the <code>args()</code> function:</p>
<pre>args(ts)
function (data = NA, start = 1, end = numeric(), frequency = 1, 
    deltat = 1, ts.eps = getOption(&quot;ts.eps&quot;), class = if (nseries > 
        1) c(&quot;mts&quot;, &quot;ts&quot;, &quot;matrix&quot;) else &quot;ts&quot;, names = if (!is.null(dimnames(data))) colnames(data) else paste(&quot;Series&quot;, 
        seq(nseries))) 
NULL</pre>
<p>To begin, we will focus on the first four arguments – <code>data</code>, <code>start</code>, <code>end</code> and <code>frequency</code>. The <code>data</code> argument is the data itself (a vector or matrix). The <code>start</code> and <code>end</code> arguments allow us to provide a start date and end date for the series. Finally the <code>frequency</code> argument lets us specify the number of observations per unit of time. For example, if we had monthly data, we would use 12 for the <code>frequency</code> argument, indicating that there are 12 months in the year.</p>
<p>Let’s assume our generated data is quarterly data that starts in the first quarter of 2000. We would turn it into a <code>ts</code> object as below. We specify the <code>start</code> argument as a two element vector. The first element is the year and the second element is the observation of that year in which the data start. Because our data is quarterly, we use 4 for the <code>frequency</code> argument.</p>
<pre>
tseries &lt;- ts(t, start = c(2000, 1), frequency = 4)
print(tseries)
<em> Qtr1 Qtr2 Qtr3 Qtr4
2000 7.076670 10.388758 23.910958 14.493559
2001 15.905014 28.005455 20.226413 9.144571
2002 14.192030 16.880366 29.568573 24.518697
2003 25.805400 24.774779 21.109112 38.508392
2004 30.484953 14.233680 33.909491 26.690460
2005 23.525234 30.474176 25.817969 28.897761
2006 30.624725 24.193147 42.864509 39.073612
2007 31.033041 48.776704 43.985250 39.934500
2008 49.265880 50.146934 50.751068 50.820482
2009 50.877424 47.566618 46.858261 47.336703
2010 46.137051 50.544579 44.142226 69.182692
2011 63.455734 48.138240 54.179806 54.733413
2012 64.459756 59.416417 62.773230 61.800173
2013 62.699907 73.580216 63.419603 76.615294
2014 56.158730 72.092296 69.866980 71.511591
2015 73.657476 68.483736 70.667548 66.869972
2016 67.497461 78.124700 80.137468 78.371030
2017 85.455872 94.350593 77.562782 65.835818
2018 90.040170 79.035595 80.183940 93.179000
2019 85.006589 79.454976 90.269124 89.027760
2020 91.040349 94.696963 90.405380 98.510636
2021 93.456594 98.322474 104.677873 101.046270
2022 96.718479 108.041653 107.954527 105.838779
2023 104.671122 99.604657 114.524567 101.798183
2024 122.311331 118.728274 107.350097 102.815054</em></pre>
<pre>plot(tseries)</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsguide2.png?ssl=1" target="_blank"><img sizes="(max-width: 1344px) 100vw, 1344px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsguide2.png?w=450&ssl=1" alt="" class="wp-image-8405" data-recalc-dims="1"></a></p>
<p>Notice that now when we plot the data, R recognizes that it is a <code>ts</code> object and plots the data as a line with dates along the x-axis.</p>
<p>Aside from creating <code>ts</code> objects containing a single series of data, we can also create <code>ts</code> objects that contain multiple series. We can do this by passing a matrix rather than a vector to the <code>x</code> argument of <code>ts()</code>.</p>
<pre>set.seed(123)
seq &lt;- seq(from = 1, to = 100, by = 1) + 10
ts1 &lt;- seq + rnorm(100, sd = 5)
ts2 &lt;- seq + rnorm(100, sd = 12)
ts3 &lt;- seq^2 + rnorm(100, sd = 300)
tsm &lt;- cbind(ts1, ts2, ts3)
tsm &lt;- ts(tsm, start=c(2000, 1), frequency = 4)
plot(tsm)</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsguide3.png?ssl=1" target="_blank"><img sizes="(max-width: 1344px) 100vw, 1344px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsguide3.png?w=450&ssl=1" alt="" class="wp-image-8406" data-recalc-dims="1"></a></p>
<p>Now when we plot the <code>ts</code> object, R automatically facets the plot.</p>
<p>At this point, I should mention what really happens when we call the <code>plot()</code> function on a <code>ts</code> object. R recognizes when the <code>x</code> argument is a <code>ts</code> object and actually calls the <code>plot.ts()</code> function under the hood. We can verify this by using it directly. Notice that it produces an identical graph.</p>
<pre>plot.ts(tsm)</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsguide4.png?ssl=1" target="_blank"><img sizes="(max-width: 1344px) 100vw, 1344px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsguide4.png?w=450&ssl=1" alt="" class="wp-image-8407" data-recalc-dims="1"></a></p>
<p>The <code>plot.ts()</code> function has different arguments geared towards time series objects. We can look at these again using the <code>args()</code> function.</p>
<pre>args(plot.ts)
function (x, y = NULL, plot.type = c(&quot;multiple&quot;, &quot;single&quot;), xy.labels, 
    xy.lines, panel = lines, nc, yax.flip = FALSE, mar.multi = c(0, 
        5.1, 0, if (yax.flip) 5.1 else 2.1), oma.multi = c(6, 
        0, 5, 0), axes = TRUE, ...) 
NULL</pre>
<p>Notice that it has an argument called <code>plot.type</code> that lets us indicate whether we want our plot to be faceted (multiple) or single-panel (single). Although in the case of our data above we would not want to plot all three series on the same panel given the difference in scale for <code>ts3</code>, it can be done quite easily.</p>
<p>I am not going to go in-depth into using R’s base plotting capability. Although it is perfectly fine, I strongly prefer to use <code>ggplot2</code> as well as the <code>ggplot</code>-based graphing functions available in Rob Hyndman’s <code>forecast</code> package. We will discuss these in later parts of this guide. </p>
<h2>Convenience Functions for Time Series</h2>
<p>There are several useful functions for use with ts objects that can make programming easier. These are <code>window()</code>, <code>start()</code>, <code>end()</code>, and <code>frequency()</code>. These are fairly self-explanatory. The <code>window</code> function is a quick and easy way to obtain a slice of a time series object. For example, look again at our object <code>tseries</code>. Assume that we wanted only the data from the first quarter of 2000 to the last quarter of 2012. We can do so using <code>window()</code>:</p>
<pre>tseries_sub &lt;- window(tseries, start=c(2000, 1), end=c(2012,4))
print(tseries_sub)
<em> Qtr1 Qtr2 Qtr3 Qtr4
2000 7.076670 10.388758 23.910958 14.493559
2001 15.905014 28.005455 20.226413 9.144571
2002 14.192030 16.880366 29.568573 24.518697
2003 25.805400 24.774779 21.109112 38.508392
2004 30.484953 14.233680 33.909491 26.690460
2005 23.525234 30.474176 25.817969 28.897761
2006 30.624725 24.193147 42.864509 39.073612
2007 31.033041 48.776704 43.985250 39.934500
2008 49.265880 50.146934 50.751068 50.820482
2009 50.877424 47.566618 46.858261 47.336703
2010 46.137051 50.544579 44.142226 69.182692
2011 63.455734 48.138240 54.179806 54.733413
2012 64.459756 59.416417 62.773230 61.800173</em></pre>
<p>The <code>start()</code> function returns the start date of a <code>ts</code> object, <code>end()</code> gives the end date, and <code>frequency()</code> returns the frequency of a given time series:</p>
<pre>start(tsm)
end(tsm)
frequency(tsm)
<em>## [1] 2000 1
## [1] 2024 4
## [1] 4</em></pre>
<p>That’s all for now. In Part 2, we’ll dive into some of the many transformation functions for working with time series in R. See you then.</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a rel="nofollow" href="https://datascienceplus.com/parsing-text-for-emotion-terms-analysis-visualization-using-r/" title="Permanent Link toParsing Text for Emotion Terms: Analysis &amp; Visualization Using R" target="_blank">Parsing Text for Emotion Terms: Analysis &amp; Visualization Using R</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/using-mongodb-with-r/" title="Permanent Link toUsing MongoDB with R" target="_blank">Using MongoDB with R</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/finding-optimal-number-of-clusters/" title="Permanent Link toFinding Optimal Number of Clusters" target="_blank">Finding Optimal Number of Clusters</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/analyzing-the-first-presidential-debate/" title="Permanent Link toAnalyzing the first Presidential Debate" target="_blank">Analyzing the first Presidential Debate</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/goodreads-machine-learning-part-3/" title="Permanent Link toGoodReads: Machine Learning (Part 3)" target="_blank">GoodReads: Machine Learning (Part 3)</a></li>
</ol></strong>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datascienceplus.com/time-series-analysis-in-r-part-1-the-time-series-object/"> R Programming – DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/FxBD5nIP5YA" height="1"></a></div>