Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return data subset time frames within another timeframes?

There are very nifty ways of subsetting xts objects. For example, one can get all the data for all years, months, days but being strictly between 9:30 AM and 4 PM by doing:

my_xts["T09:30/T16:00"]

Or you can get all the observations between two dates by doing:

my_xts["2012-01-01/2012-03-31"]

Or all the dates before/after a certain date by doing:

my_xts["/2011"]  # from start of data until end of 2011
my_xts["2011/"]  # from 2011 until the end of the data

How can I get all the data for only certain months for all years or only certain days for all months and years? Do any other subsetting tricks exist?

like image 830
Alex Avatar asked Aug 08 '12 19:08

Alex


2 Answers

You can use the .index* family of functions to get certain months or certain days of the month. See ?index for the full list of functions. For example:

library(quantmod)
getSymbols("SPY")
SPY[.indexmon(SPY)==0]   # January for all years (note zero-based indexing!)
SPY[.indexmday(SPY)==1]  # The first of every month
SPY[.indexwday(SPY)==1]  # All Mondays
like image 116
Joshua Ulrich Avatar answered Nov 17 '22 11:11

Joshua Ulrich


time-of-day subsetting is a little bit hidden, so I understand why it would spark a question like this. The only other 'trick' I know is the last and first functions, which you can nest if you need to. e.g. this will get the last 2 days of the first 3 weeks.

last(first(my_xts, "3 weeks"), "2 days")
like image 15
GSee Avatar answered Nov 17 '22 11:11

GSee