Skip to main content

xts Cheat Sheet: Time Series in R

Get started on time series in R with this xts cheat sheet, with code examples.
Jul 2021  · 5 min read

Even though the data.frame 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.

 xts  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 zoo, which is the package that is the creator for an S3 class of indexed totally ordered observations which includes irregular time series.

xts 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. 

This xts cheat sheet provides you not only with an overview of the xts object, how to create and inspect them, but also goes deeper into how you can manipulate time series with xts: 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.

Click on the button below to see (and download) the xts cheat sheet: 

Have this cheat sheet at your fingertips

Download PDF

This cheat sheet will help you to get yourself up to speed in no time! 

R For Data Science Cheat Sheet: xts

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.

Load the package as follows:


Xts Objects

xts objects have three main components:

  • coredata: always a matrix for xts objects
  • index: vector of any Date, POSIXct, chron, yearmon, yearqtr, or DateTime classes
  • xtsAttributes: arbitrary attributes

Creating xts Objects

xts1 <- xts(x=1:10,
data <- rnorm(5)
dates <- seq(as.Date("2017-05-01"), length=5, by="days")
xts2 <- xts(x=data,
xts3 <- xts(x=rnorm(10),, born=as.POSIXct("1899-05-08")
xts4 <- xts(x=1:10,

Convert To And From xts

xts5 <- as.xts(AirPassengers)

Import From Files

dat <- read.csv(tmp_file)
dat_zoo <- read.zoo(tmp_file, index.column=0, sep=",", format="%m/%d/%Y")
dat_zoo <- read.zoo(tmp,sep=",",FUN=as.yearmon)
dat_xts <- as.xts(dat_zoo)

Inspect Your Data

Extract core data of objects

core_data <- coredata(xts2)

Extract index from objects


Class Attributes

Get index class


Replacing index class


Get index class


Change format of time display

indexFormat(xts5) <- "%Y-%m-%d"

Time Zones

Change the time zone

tzone(xts1) <- "Asia/Hong_Kong"

Extract the current time zone


Periods, Periodicity & Timestamps

Estimate frequency of observations


Convert xts5 to yearly OHLC


Convert xts3 to monthly OHLC


Convert xts5 to quarterly OHLC


Convert to quarterly OHLC


Convert to yearly OHLC


Count the months in xts5


Count the quarters in xts5


Count the years in xts5


Make index unique


Remove duplicate times


Round index time to the next n seconds

align.time(xts3, n=3600)

Other Useful Functions

Extract raw numeric index of xts1


value of weekday in index of xts3


Value of hour in index of xts3


Extract first observation of xts3 


Extract last observation of xts4 


Display structure of xts3 


Extract raw numeric index of xts1


First part of xts2


Last part of xts2 


Export xts Objects

data_xts <- as.xts(matrix)
tmp <- tempfile()

Replace & Update

Replace values in xts2 on dates with 0 

xts2[dates] <- 0 

Replace dates from 1961 with NA 

xts5["1961"] <- NA

Replace the value at 1 specific index with NA

 xts2["2016-05-02"] <- NA  

Applying Functions

Locate endpoints by time 

ep1 <- endpoints(xts4,on="weeks",k=2)  
ep2 <- endpoints(xts5,on="years")

Calculate the yearly mean 


Split xts5 by year

xts5_yearly <- split(xts5,f="years")

Create a list of yearly means   


Find the last observation in each year in xts5,  lapply(split(xts5,"years"), function(w) last(w,n="1 month")))

Calculate cumulative annual passengers,  lapply(split(xts5,"years"),  cumsum))

Apply standard deviation to rolling margins of xts5

rollapply(xts5, 3, sd) 

Selecting, Subsetting & Indexing


mar55 <- xts5["1955-03"] #Get value for March 1955


Get all data from 1954 

xts5_1954 <- xts5["1954"] 

Extract data from Jan to March ‘54 

xts5_janmarch <- xts5["1954/1954-03"]

Get all data until March ‘54  

xts5_janmarch <- xts5["/1954-03"] 

Subset xts4 using ep2 


first() and last()

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


Extract rows with the index of xts3 


Extract rows using the vector days 

days <- c("2017-05-03","2017-05-23") 

Extract rows using days as POSIXct 


Index of weekend days


Extract weekend days of xts1 


Missing Values

Omit NA values in xts5 


Fill missing values in xts2 using last observation

xts_last <- na.locf(xts2)

Fill missing values in xts2 using next observation

xts_last <- na.locf(xts2,  fromLast=TRUE)

Interpolate NAs


Arithmetic Operations

coredata() or as.numeric()

xts3 + as.numeric(xts2) #Addition
xts3 * as.numeric(xts4) #Multiplication
coredata(xts4) - xts3 #Subtraction
coredata(xts4) / xts3 #Division

Shifting Index Values

Period-over-period differences 

xts5 - lag(xts5)

Lagged differences



xts1 + merge(xts2,index(xts1),fill=0) #Addition
xts1 - merge(xts2,index(xts1),fill=na.locf) #Subtraction


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)

Going Further

Want to know more about xts? Check out DataCamp's Manipulating Time Series Data in R with xts & zoo course! 

Data Science Concept Vector Image

How to Become a Data Scientist in 8 Steps

Find out everything you need to know about becoming a data scientist, and find out whether it’s the right career for you!
Jose Jorge Rodriguez Salgado's photo

Jose Jorge Rodriguez Salgado

12 min

Predicting FIFA World Cup Qatar 2022 Winners

Learn to use Elo ratings to quantify national soccer team performance, and see how the model can be used to predict the winner of FIFA World Cup Qatar 2022.

Arne Warnke

DC Data in Soccer Infographic.png

How Data Science is Changing Soccer

With the Fifa 2022 World Cup upon us, learn about the most widely used data science use-cases in soccer.
Richie Cotton's photo

Richie Cotton

Regular Expressions Cheat Sheet

Regular expressions (regex or regexp) are a pattern of characters that describe an amount of text. Regular expressions are one of the most widely used tools in natural language processing and allow you to supercharge common text data manipulation tasks. Use this cheat sheet as a handy reminder when working with regular expressions.
DataCamp Team's photo

DataCamp Team

ggplot2 Cheat Sheet

ggplot2 is considered to be one of the most robust data visualization packages in any programming language. Use this cheat sheet to guide your ggplot2 learning journey.
DataCamp Team's photo

DataCamp Team

A Guide to R Regular Expressions

Explore regular expressions in R, why they're important, the tools and functions to work with them, common regex patterns, and how to use them.
Elena Kosourova 's photo

Elena Kosourova

16 min

See MoreSee More