[R-SIG-Finance] xts question: how to get previous row?
Sandor Benczik
sandor.benczik at crabel.ro
Mon Jul 13 13:22:28 CEST 2009
You may try this:
> getSymbols("AAPL")
> prev.idx <- which(index(AAPL["2007-01-08"])==index(AAPL))-1
> AAPL[prev.idx]
It should be slightly faster than grep-ing, but still does not do binary
search.
OTOH, I don't think Dirk's suggestion will work if you have gaps
(missing days) in the data. Say:
> Z <- xts(100+cumsum(rnorm(10)), order.by=as.Date("2009-07-01")+0:9*2)
> Z[ index(Z["2009-07-07"]) - 1, ]
Data:
numeric(0)
Index:
integer(0)
HTH,
Sandor
| -----Original Message-----
| From: r-sig-finance-bounces at stat.math.ethz.ch [mailto:r-sig-finance-
| bounces at stat.math.ethz.ch] On Behalf Of Dirk Eddelbuettel
| Sent: Monday, July 13, 2009 12:27 PM
| To: Mark Breman
| Cc: r-sig-finance at stat.math.ethz.ch
| Subject: Re: [R-SIG-Finance] xts question: how to get previous row?
|
|
| 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.
|
| _______________________________________________
| R-SIG-Finance at stat.math.ethz.ch mailing list
| https://stat.ethz.ch/mailman/listinfo/r-sig-finance
| -- Subscriber-posting only.
| -- If you want to post, subscribe first.
More information about the R-SIG-Finance
mailing list