<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/packages-for-getting-started-with-time-series-analysis-in-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://mathewanalytics.com/2018/02/18/packages-for-getting-started-with-time-series-analysis-in-r/"> R – Mathew Analytics</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>A. Motivation</p>
<p>During the recent RStudio Conference, an attendee asked the panel about the lack of support provided by the tidyverse in relation to time series data. As someone who has spent the majority of their career on time series problems, this was somewhat surprising because R already has a great suite of tools for visualizing, manipulating, and modeling time series data. I can understand the desire for a ‘tidyverse approved’ tool for time series analysis, but it seemed like perhaps the issue was a lack of familiarity with the available toolage. Therefore, I wanted to put together a list of the packages and tools that I use most frequently in my work. For those unfamiliar with time series analysis, this could a good place to start investigating Rs current capabilities.</p>
<p>B. Background</p>
<p>Time series data refers to a sequence of measurements that are made over time at regular or irregular intervals with each observation being a single dimension. An example of low dimensional time series is daily wind temperature from 01/01/2001 through 12/31/2005. High dimensional time series is characterized by a larger number of observations, so an example could be the daily wind temperature from 01/01/1980 through 12/31/2010. In either case, the goal of the analysis could lead one to perform regression, clustering, forecasting, or even classification.</p>
<p>C. Data For Examples</p>
<p>To run the code in this post, you will need to access the following data through the unix terminal. It will download a csv file from the City of Chicago website that contains<br>
information on reported incidents of crime that occurred in the city of Chicago from 2001 to present.</p>
<pre>
$ wget –no-check-certificate –progress=dot https://data.cityofchicago.org/api/views/ijzp-q8t2/rows.csv?accessType=DOWNLOAD > chicago_crime_data.csv
</pre>
<p>Import the data into R and get the aggregate number of reported incidents of theft by day.</p>
<pre>
library(data.table)
dat = fread(&quot;chicago_crime_data.csv&quot;)
colnames(dat) = gsub(&quot; &quot;, &quot;_&quot;, tolower(colnames(dat)))
dat[, date2 := as.Date(date, format=&quot;%m/%d/%Y&quot;)]
mydat = dat[primary_type==&quot;THEFT&quot;, .N, by=date2][order(date2)]
mydat[1:6]
</pre>
<p>D. Data Representation</p>
<p>The first set of packages that one should be aware of is related to data storage. One could use data frames, tibbles, or data tables, but there are already a number of data structures that are optimized for representing time series data. The fundamental time series object is “ts”. However, the “ts” class has a number of limitations, and so it is usually best to work with the extensible time series (“xts”) obect.</p>
<p>D1. xts</p>
<p>The xts package offers a number of great tools for data manipulation and aggregation. At it’s core is the xts object, which is essentially a matrix object that can represent time series data at different time increments. Xts is a subclass of the zoo object, and that provides it with a lot of functionality.</p>
<p>Here are some functions in xts that are worth investigating:</p>
<pre>
library(xts)
# create a xts object 
mydat2 = as.xts(mydat)
mydat2
plot.xts(mydat2)
# filter by date 
mydat2[&quot;2015&quot;]  ## 2015
mydat2[&quot;201501&quot;]  ## Jan 2015
mydat2[&quot;20150101/20150105&quot;]  ## Jan 01 to Jan 05 2015 
# replace all valuues from Aug 25 onwards with 0
mydat2[&quot;20170825/&quot;] &lt;- 0
mydat2[&quot;20170821/&quot;]
# get the last one month 
last(mydat2, &quot;1 month&quot;)
# get stats by time frame
apply.monthly(mydat2, sum)
apply.monthly(mydat2, quantile)
period.apply(mydat2, endpoints(mydat2,on='months'), sum)
period.apply(mydat2, endpoints(mydat2,on='months'), quantile)
</pre>
<p>E. Dates</p>
<p>R has a maddening array of date and time classes. Be it yearmon, POSIXct, POSIXlt, chron, or something else, each has specific strengths and weaknesses. In general, I find myself using the lubridate package as it simplifies many of the complexities associated with date-times in R.</p>
<p>E1. lubridate</p>
<p>The lubridate package provides a lot of functionality for parsing and formatting<br>
dates, comparing different times, extracting the components of a date-time, and so<br>
forth.</p>
<pre>
library(lubridate)
ymd(&quot;2010-01-01&quot;)
mdy(&quot;01-01-2010&quot;)
ymd_h(&quot;2010-01-01 10&quot;)
ymd_hm(&quot;2010-01-01 10:02&quot;)
ymd_hms(&quot;2010-01-01 10:02:30&quot;)
</pre>
<p>F. Time Series Regression</p>
<p>Distributed lag models (error correction models) are a core component of doing time series analysis. They are many instances where we want to regress an outcome variable at the current time against values of various regressors at current and previous times. dynlm and ardl (wrapper for dynlm) are solid for this type of analysis. Another common task when working with distributed lag models involves using dynamic simulations to understand estimated outcomes in different scenarios. dynsim provides a coherent solution for simulation and visualization of those estimated values of the target variable.</p>
<p>F1. dynlm / ardl</p>
<p>Here is a brief example of how dynlm can be utilized. In what follows, I have created a new variable and lagged it by one day. So the model attempts to regress incidents or reported theft based on the weather from the previous day.</p>
<pre>
library(dynlm)
mydat = dat[primary_type==&quot;THEFT&quot;, .N, by=date2][order(date2)]
mydat[, weather := sample(c(20:90), dim(mydat), replace=TRUE)]
mydat[, weather_lag := shift(weather, 1, type = 'lag')]
mod = dynlm(N ~ L(weather), data = mydat2)
summary(mod)
</pre>
<p>F2. dynsim</p>
<p>Here is a brief example of how dynlm can be utilized. In what follows, I have created a new variable and lagged it by one day. I’ve used the dynsim to product two dynamic simulations and plotted them.</p>
<pre>
library(dynsim)
mydat3 = mydat[1:10000]
mod = lm(N ~ weather_lag, data = mydat3)
Scen1 &lt;- data.frame(weather_lag = min(mydat2$weather_lag, na.rm=T))
Scen2 &lt;- data.frame(weather_lag = max(mydat2$weather_lag, na.rm=T))
ScenComb &lt;- list(Scen1, Scen2)
Sim1 &lt;- dynsim(obj = mod, ldv = 'weather_lag', scen = ScenComb, n = 20)
dynsimGG(Sim1)
</pre>
<p>D. Forecasting</p>
<p>D1. forecast</p>
<p>The forecast package is the most used package in R for time series forecasting. It contains functions for performing decomposition and forecasting with exponential smoothing, arima, moving average models, and so forth. For aggregated data that is fairly high dimensional, one of the techniques present in this package should provide an adequate forecasting model given that the assumptions hold.</p>
<p>Here is a quick example of how to use the auto.arima function in R. In general, automatic forecasting tools should be used with caution, but it is a good place to explore time series data.</p>
<pre>
library(forecast)
mydat = dat[primary_type==&quot;THEFT&quot;, .N, by=date2][order(date2)]
fit = auto.arima(mydat[,.(N)])
pred = forecast(fit, 200)
plot(pred)
</pre>
<p>D2. smooth</p>
<p>The smooth package provides functions to perform even more variations of exponential smoothing, moving average models, and various seasonal arima techniques. The smooth and forecast package are usually more than adequate for most forecasting problems that pertain to high dimensional data.</p>
<p>Here is a basic example that uses the automatic complex exponential smoothing function:</p>
<pre>
library(smooth)
mydat = dat[primary_type==&quot;THEFT&quot;, .N, by=date2][order(date2)]
fit = auto.ces(mydat[,N])
pred = forecast(fit, 200)
plot(pred)
</pre>
<p>So for those of you getting introduced to the R programming language, these are a list extremely useful packages for time series analysis that you will want to get some exposure to.</p>
<p><strong>Have questions, comments, interesting consulting projects, or work that needs done, feel free to contact me at mathewanalytics@gmail.com</strong></p>
	<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://mathewanalytics.com/2018/02/18/packages-for-getting-started-with-time-series-analysis-in-r/"> R – Mathew Analytics</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/JZZfvytclWo" height="1"></a></div>