[RSIGFinance] 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["20070108"])==index(AAPL))1
> AAPL[prev.idx]
It should be slightly faster than greping, 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("20090701")+0:9*2)
> Z[ index(Z["20090707"])  1, ]
Data:
numeric(0)
Index:
integer(0)
HTH,
Sandor
 Original Message
 From: rsigfinancebounces at stat.math.ethz.ch [mailto:rsigfinance
 bounces at stat.math.ethz.ch] On Behalf Of Dirk Eddelbuettel
 Sent: Monday, July 13, 2009 12:27 PM
 To: Mark Breman
 Cc: rsigfinance at stat.math.ethz.ch
 Subject: Re: [RSIGFinance] 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
  20070420 90.97
  20070423 93.51
  20070424 93.24
  20070425 95.35
  20070426 98.84
  20070427 99.92
  20070430 99.80
  20070501 99.47
  20070502 100.39
  20070503 100.40
  20070504 100.81
 
  and supose I have a reference to a row in this series (i.e.
  aapl["20070430"]), what is the easiest way to select the previous
row
  (i.e. the row with index 20070427) 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("20090701")+0:9)
 R> Z
 [,1]
 20090701 100.08
 20090702 99.83
 20090703 100.00
 20090704 98.81
 20090705 97.62
 20090706 97.84
 20090707 98.82
 20090708 98.56
 20090709 98.37
 20090710 98.06
 R> Z[ index(Z["20090707"])  1, ]
 [,1]
 20090706 97.84
 R>


 Hth, Dirk

 
 Three out of two people have difficulties with fractions.

 _______________________________________________
 RSIGFinance at stat.math.ethz.ch mailing list
 https://stat.ethz.ch/mailman/listinfo/rsigfinance
  Subscriberposting only.
  If you want to post, subscribe first.
More information about the RSIGFinance
mailing list