Question

I know how to get data for a specific date, or a sequence with a specific date from an XTS object.

But how can I get data from x-days ago from an XTS?

Let's say the latest date in my XTS is today and I want to extract the data row one week ago. How would that look like?

Was it helpful?

Solution

An example dataset:

library(xts)
data(sample_matrix)
sample.xts <- as.xts(sample_matrix, descr='my new xts object')

> head(sample.xts)
#                Open     High      Low    Close
# 2007-01-02 50.03978 50.11778 49.95041 50.11778
# 2007-01-03 50.23050 50.42188 50.23050 50.39767
# 2007-01-04 50.42096 50.42096 50.26414 50.33236
# 2007-01-05 50.37347 50.37347 50.22103 50.33459
# 2007-01-06 50.24433 50.24433 50.11121 50.18112
# 2007-01-07 50.13211 50.21561 49.99185 49.99185

You can use the mathematical operators + and - with dates.

refDate <- as.Date("2007-01-07") # a reference date

sample.xts[refDate]
#                Open     High      Low    Close
# 2007-01-07 50.13211 50.21561 49.99185 49.99185

sample.xts[refDate - 3] # 3 days before
#                Open     High      Low    Close
# 2007-01-04 50.42096 50.42096 50.26414 50.33236

By the way: You can obtain the date of today with Sys.Date().

Sys.Date()
# [1] "2013-12-10"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top