<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/xts-cheat-sheet-time-series-in-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.datacamp.com/community/blog/r-xts-cheat-sheet"> DataCamp Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<section>
<p>Even though the <code>data.frame</code> object is one of the core objects to hold data in R, you’ll find that it’s not really efficient when you’re working with time series data. You’ll find yourself wanting a more flexible time series class in R that offers a variety of methods to manipulate your data.</p>
<p><code>xts</code>  or the Extensible Time Series is one of such packages that offers such a time series object. It’s a powerful R package that provides an extensible time series class, enabling uniform handling of many R time series classes by extending <code>zoo</code>, which is the package that is the creator for an S3 class of indexed totally ordered observations which includes irregular time series.</p>
<p><code><tt>xts</tt></code> has a lot to offer to make your time series analysis fast and mistake free, but it can take some time to get used to it. </p>
<p>This <code>xts</code> cheat sheet provides you not only with an overview of the <code>xts</code> object, how to create and inspect them, but also goes deeper into how you can manipulate time series with <code>xts</code>: you’ll see how to replace and update values, how to select, index and subset your objects, how to handle missing values and how to perform arithmetic operations.</p>
<p>Click on the button below to see (and download) the xts cheat sheet: </p>
<p><a target="_blank" rel="nofollow" href="https://s3.amazonaws.com/assets.datacamp.com/blog_assets/xts_Cheat_Sheet_R.pdf?tap_a=5644-dce66f&tap_s=10907-287229"><img alt="" src="https://i2.wp.com/community.datacamp.com.s3.amazonaws.com/community/production/ckeditor_assets/pictures/542/content_button-cheatsheet-xts.png?w=456" data-recalc-dims="1"></a></p>
<p><strong>(Click above to download a printable version or read the online version below.) </strong></p>
<p>This cheat sheet will help you to get yourself up to speed in no time! </p>
<div>

<h2>R For Data Science Cheat Sheet: xts</h2>
<p>eXtensible Time Series (xts) is a powerful package that provides an extensible time series class, enabling uniform handling of many R time series classes by extending zoo.</p>
<p>Load the package as follows:</p>
<pre>
<code>library(xts)</code></pre>
<h3>Xts Objects</h3>
<p>xts objects have three main components:</p>
<ul>
<li>coredata: always a matrix for xts objects</li>
<li>index: vector of any <code>Date</code>, <code>POSIXct</code>, <code>chron</code>, <code>yearmon</code>, <code>yearqtr</code>, or <code>DateTime</code> classes</li>
<li>xtsAttributes: arbitrary attributes</li>
</ul>
<h2>Creating xts Objects</h2>
<pre>
<code>xts1 &lt;- xts(x=1:10, order.by=Sys.Date()-1:10)
data &lt;- rnorm(5)
dates &lt;- seq(as.Date(&quot;2017-05-01&quot;), length=5, by=&quot;days&quot;)
xts2 &lt;- xts(x=data, order.by=dates)
xts3 &lt;- xts(x=rnorm(10), order.by=as.POSIXct(Sys.Date()+1:10), born=as.POSIXct(&quot;1899-05-08&quot;)
xts4 &lt;- xts(x=1:10, order.by=Sys.Date()+1:10)</code></pre>
<h3>Convert To And From xts</h3>
<pre>
<code>data(AirPassengers)
xts5 &lt;- as.xts(AirPassengers)</code></pre>
<h3>Import From Files</h3>
<pre>
<code>dat &lt;- read.csv(tmp_file)
xts(dat, order.by=as.Date(rownames(dat),&quot;%m/%d/%Y&quot;))
dat_zoo &lt;- read.zoo(tmp_file, index.column=0, sep=&quot;,&quot;, format=&quot;%m/%d/%Y&quot;)
dat_zoo &lt;- read.zoo(tmp,sep=&quot;,&quot;,FUN=as.yearmon)
dat_xts &lt;- as.xts(dat_zoo)</code></pre>
<h2>Inspect Your Data</h2>
<p>Extract core data of objects</p>
<pre>
<code>core_data &lt;- coredata(xts2)</code></pre>
<p>Extract index from objects</p>
<pre>
<code>index(xts1)</code></pre>
<h3>Class Attributes</h3>
<p>Get index class</p>
<pre>
<code>indexClass(xts2)</code></pre>
<p>Replacing index class</p>
<pre>
<code>indexClass(convertIndex(xts,'POSIXct'))</code></pre>
<p>Get index class</p>
<pre>
<code>indexTZ(xts5)</code></pre>
<p>Change format of time display</p>
<pre>
<code>indexFormat(xts5) &lt;- &quot;%Y-%m-%d&quot;</code></pre>
<h3>Time Zones</h3>
<p>Change the time zone</p>
<pre>
<code>tzone(xts1) &lt;- &quot;Asia/Hong_Kong&quot;</code></pre>
<p>Extract the current time zone</p>
<pre>
<code>tzone(xts1)</code></pre>
<h3>Periods, Periodicity &amp; Timestamps</h3>
<p>Estimate frequency of observations</p>
<pre>
<code>periodicity(xts5)</code></pre>
<p>Convert xts5 to yearly OHLC</p>
<pre>
<code>to.yearly(xts5)</code></pre>
<p>Convert <code>xts3</code> to monthly OHLC</p>
<pre>
<code>to.monthly(xts3)</code></pre>
<p>Convert <code>xts5</code> to quarterly OHLC</p>
<pre>
<code>to.quarterly(xts5)</code></pre>
<p>Convert to quarterly OHLC</p>
<pre>
<code>to.period(xts5,period=&quot;quarters&quot;)</code></pre>
<p>Convert to yearly OHLC</p>
<pre>
<code>to.period(xts5,period=&quot;years&quot;)</code></pre>
<p>Count the months in <code>xts5</code></p>
<pre>
<code>nmonths(xts5)</code></pre>
<p>Count the quarters in <code>xts5</code></p>
<pre>
<code>nquarters(xts5)</code></pre>
<p>Count the years in <code>xts5</code></p>
<pre>
<code>nyears(xts5)</code></pre>
<p>Make index unique</p>
<pre>
<code>make.index.unique(xts3,eps=1e-4)</code></pre>
<p>Remove duplicate times</p>
<pre>
<code>make.index.unique(xts3,drop=TRUE)</code></pre>
<p>Round index time to the next <code>n</code> seconds</p>
<pre>
<code>align.time(xts3, n=3600)</code></pre>
<h3>Other Useful Functions</h3>
<p>Extract raw numeric index of <code><tt>xts1</tt></code></p>
<pre>
<code>.index(xts4)</code></pre>
<p>value of weekday in index of <code>xts3</code></p>
<pre>
<code>.indexwday(xts3)</code></pre>
<p>Value of hour in index of <code>xts3</code></p>
<pre>
<code>.indexhour(xts3)</code></pre>
<p>Extract first observation of <code>xts3</code></p>
<pre>
<code>start(xts3)</code></pre>
<p>Extract last observation of <code>xts4</code></p>
<pre>
<code>end(xts4)</code></pre>
<p>Display structure of <code>xts3</code></p>
<pre>
<code>str(xts3) </code></pre>
<p>Extract raw numeric index of <code>xts1</code></p>
<pre>
<code>time(xts1)</code></pre>
<p>First part of <code>xts2</code></p>
<pre>
<code>head(xts2)</code></pre>
<p>Last part of <code>xts2</code></p>
<pre>
<code>tail(xts2)</code></pre>

<h2>Export <code>xts</code> Objects</h2>
<pre>
<code>data_xts &lt;- as.xts(matrix)
tmp &lt;- tempfile()
write.zoo(data_xts,sep=&quot;,&quot;,file=tmp)</code></pre>
<h2>Replace &amp; Update</h2>
<p>Replace values in <code>xts2</code> on dates with <code><tt>0</tt></code></p>
<pre>
<code>xts2[dates] &lt;- 0 </code></pre>
<p>Replace dates from 1961 with <code>NA</code></p>
<pre>
<code>xts5[&quot;1961&quot;] &lt;- NA</code></pre>
<p>Replace the value at 1 specific index with <code>NA</code></p>
<pre>
<code>xts2[&quot;2016-05-02&quot;] &lt;- NA </code></pre>

<h2>Applying Functions</h2>
<p>Locate endpoints by time </p>
<pre>
<code>ep1 &lt;- endpoints(xts4,on=&quot;weeks&quot;,k=2)  
ep2 &lt;- endpoints(xts5,on=&quot;years&quot;) </code></pre>
<p>Calculate the yearly mean </p>
<pre>
<code>period.apply(xts5,INDEX=ep2,FUN=mean)</code></pre>
<p>Split <code>xts5</code> by year</p>
<pre>
<code>xts5_yearly &lt;- split(xts5,f=&quot;years&quot;)</code></pre>
<p>Create a list of yearly means   </p>
<pre>
<code>lapply(xts5_yearly,FUN=mean) </code></pre>
<p>Find the last observation in each year in <code>xts5</code></p>
<pre>
<code>do.call(rbind,  lapply(split(xts5,&quot;years&quot;), function(w) last(w,n=&quot;1 month&quot;))) </code></pre>
<p>Calculate cumulative annual passengers</p>
<pre>
<code>do.call(rbind,  lapply(split(xts5,&quot;years&quot;),  cumsum)) </code></pre>
<p>Apply standard deviation to rolling margins of <code>xts5</code></p>
<pre>
<code>rollapply(xts5, 3, sd)  </code></pre>
<h2>Selecting, Subsetting &amp; Indexing</h2>
<h3>Select</h3>
<pre>
<code>mar55 &lt;- xts5[&quot;1955-03&quot;] #Get value for March 1955</code></pre>
<h3>Subset</h3>
<p>Get all data from 1954 </p>
<pre>
<code>xts5_1954 &lt;- xts5[&quot;1954&quot;] </code></pre>
<p>Extract data from Jan to March ‘54 </p>
<pre>
<code>xts5_janmarch &lt;- xts5[&quot;1954/1954-03&quot;]</code></pre>
<p>Get all data until March ‘54  </p>
<pre>
<code>xts5_janmarch &lt;- xts5[&quot;/1954-03&quot;] </code></pre>
<p>Subset <code>xts4</code> using <code>ep2</code></p>
<pre>
<code>xts4[ep1] </code></pre>
<h3>
<code>first()</code> and <code>last()</code><br>
</h3>
<pre>
<code>first(xts4,'1 week') #Extract first 1 week
first(last(xts4,'1 week'),'3 days') #Get first 3 days of the last week of data</code></pre>
<h3>Indexing</h3>
<p>Extract rows with the index of <code>xts3</code></p>
<pre>
<code>xts2[index(xts3)] </code></pre>
<p>Extract rows using the vector <code>days</code></p>
<pre>
<code>days &lt;- c(&quot;2017-05-03&quot;,&quot;2017-05-23&quot;) 
xts3[days] </code></pre>
<p>Extract rows using <code>days</code> as <code>POSIXct</code></p>
<pre>
<code>xts2[as.POSIXct(days,tz=&quot;UTC&quot;)] </code></pre>
<p>Index of weekend days</p>
<pre>
<code>index&lt;-which(.indexwday(xts1)==0|.indexwday(xts1)==6) </code></pre>
<p>Extract weekend days of <code>xts1</code></p>
<pre>
<code>xts1[index] </code></pre>
<h2>Missing Values</h2>
<p>Omit NA values in <code>xts5</code></p>
<pre>
<code>na.omit(xts5) </code></pre>
<p>Fill missing values in <code>xts2</code> using last observation</p>
<pre>
<code>xts_last &lt;- na.locf(xts2) </code></pre>
<p>Fill missing values in <code>xts2</code> using next observation</p>
<pre>
<code>xts_last &lt;- na.locf(xts2,  fromLast=TRUE)</code></pre>
<p>Interpolate <code>NA</code>s</p>
<pre>
<code>na.approx(xts2)  </code></pre>
<h2>Arithmetic Operations</h2>
<h3>
<code>coredata()</code> or <code>as.numeric()</code><br>
</h3>
<pre>
<code>xts3 + as.numeric(xts2) #Addition
xts3 * as.numeric(xts4) #Multiplication
coredata(xts4) - xts3 #Subtraction
coredata(xts4) / xts3 #Division</code></pre>
<h3>Shifting Index Values</h3>
<p>Period-over-period differences </p>
<pre>
<code>xts5 - lag(xts5) </code></pre>
<p>Lagged differences</p>
<pre>
<code>diff(xts5,lag=12,differences=1) </code></pre>
<h3>Reindexing</h3>
<pre>
<code>xts1 + merge(xts2,index(xts1),fill=0) #Addition
xts1 - merge(xts2,index(xts1),fill=na.locf) #Subtraction</code></pre>
<h2>Merging</h2>
<pre>
<code>merge(xts2,xts1,join='inner') # Inner join of xts2 and xts1
merge(xts2,xts1,join='left',fill=0) #Left join of xts2 and xts1,
rbind(xts1, xts4)</code></pre>
<h2>Going Further</h2>
<p>Want to know more about <code>xts</code>? Check out DataCamp’s <a target="_blank" rel="nofollow" href="https://www.datacamp.com/courses/manipulating-time-series-data-in-r-with-xts-zoo?tap_a=5644-dce66f&tap_s=10907-287229">Manipulating Time Series Data in R with </a><a target="_blank" rel="nofollow" href="https://www.datacamp.com/courses/manipulating-time-series-data-in-r-with-xts-zoo?tap_a=5644-dce66f&tap_s=10907-287229">xts</a><a target="_blank" rel="nofollow" href="https://www.datacamp.com/courses/manipulating-time-series-data-in-r-with-xts-zoo?tap_a=5644-dce66f&tap_s=10907-287229"> &amp; zoo</a> course! </p>
</div>
</section>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.datacamp.com/community/blog/r-xts-cheat-sheet"> DataCamp Blog</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 title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/RTxzFDWG2nk"></a></div>