[R-SIG-Finance] xts question: how to get previous row?
Dirk Eddelbuettel
edd at debian.org
Mon Jul 13 11:26:59 CEST 2009
On 13 July 2009 at 08:57, Mark Breman wrote:
| I have a really basic question but I can't find an answer for it.
|
| Supose I have this xts timeseries called aapl:
| AAPL.Close
| 2007-04-20 90.97
| 2007-04-23 93.51
| 2007-04-24 93.24
| 2007-04-25 95.35
| 2007-04-26 98.84
| 2007-04-27 99.92
| 2007-04-30 99.80
| 2007-05-01 99.47
| 2007-05-02 100.39
| 2007-05-03 100.40
| 2007-05-04 100.81
|
| and supose I have a reference to a row in this series (i.e.
| aapl["2007-04-30"]), what is the easiest way to select the previous row
| (i.e. the row with index 2007-04-27) from the series?
This has nothing to do with Finance. You may want to read up on the R functions
index()
which()
as.Date()
to see just how easy xts makes the indexing. In a nutshell, use index() to
extract the position of the date(s) you want. This gives you the same 'type'
as the indexing is done one. Here, these are dates which you can add/subtract
from so a simple '- 1' gives you the previous day. You could use lag
operators.
R> Z <- xts(100+cumsum(rnorm(10)), order.by=as.Date("2009-07-01")+0:9)
R> Z
[,1]
2009-07-01 100.08
2009-07-02 99.83
2009-07-03 100.00
2009-07-04 98.81
2009-07-05 97.62
2009-07-06 97.84
2009-07-07 98.82
2009-07-08 98.56
2009-07-09 98.37
2009-07-10 98.06
R> Z[ index(Z["2009-07-07"]) - 1, ]
[,1]
2009-07-06 97.84
R>
Hth, Dirk
--
Three out of two people have difficulties with fractions.
More information about the R-SIG-Finance
mailing list