Return data subset time frames within another timeframes?

冷暖自知 提交于 2019-11-26 10:09:33

问题


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?


回答1:


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



回答2:


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")



回答3:


Be aware that there appears to be different behavior for xts subsetting of a yearmon date format for windows and ubuntu.

library(quantmod)
library(xts)

getSymbols("SPY", src="google", from = "2004-01-01")
x1 <- SPY['2006-01/2007-12']

x2 <- apply.monthly(x1,mean)
x2['2006-01/2007-12']

x3 <- as.xts(coredata(x2),order.by = as.yearmon(index(x2)))
x3['2006-01/2007-12']

The result for x2 is consistent between windows and ubuntu, since the format is full date. However, the x3 will produce different result for windows and ubuntu, after the conversion of the dates to yearmon.



来源:https://stackoverflow.com/questions/11871572/return-data-subset-time-frames-within-another-timeframes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!