user1223862
user1223862

Reputation: 1203

R Search for a particular time from index

I use an xts object. The index of the object is as below. There is one for every hour of the day for a year.

"2011-01-02 18:59:00 EST"
"2011-01-02 19:58:00 EST"
"2011-01-02 20:59:00 EST"

In columns are values associated with each index entry. What I want to do is calculate the standard deviation of the value for all Mondays at 18:59 for the complete year. There should be 52 values for the year.

I'm able to search for the day of the week using the weekdays() function, but my problem is searching for the time, such as 18:59:00 or any other time.

Upvotes: 2

Views: 317

Answers (2)

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

You can do this by using interaction to create a factor from the combination of weekdays and .indexhour, then use split to select the relevant observations from your xts object.

set.seed(21)
x <- .xts(rnorm(1e4), seq(1, by=60*60, length.out=1e4))
groups <- interaction(weekdays(index(x)), .indexhour(x))
output <- lapply(split(x, groups), function(x) c(count=length(x), sd=sd(x)))
output <- do.call(rbind, output)
head(output)
#            count        sd
# Friday.0      60 1.0301030
# Monday.0      59 0.9204670
# Saturday.0    60 0.9842125
# Sunday.0      60 0.9500347
# Thursday.0    60 0.9506620
# Tuesday.0     59 0.8972697

Upvotes: 1

hvollmeier
hvollmeier

Reputation: 2986

You can use the .index* family of functions (don't forget the '.' in front of 'index'!):

fxts[.indexmon(fxts)==0]   # its zero-based (!) and gives you all the January values
fxts[.indexmday(fxts)==1]  # beginning of month
fxts[.indexwday(SPY)==1]   # Mondays

require(quantmod)

> fxts
                value
2011-01-02 19:58:00     1
2011-01-02 20:59:00     2
2011-01-03 18:59:00     3
2011-01-09 19:58:00     4
2011-01-09 20:59:00     5
2011-01-10 18:59:00     6
2011-01-16 18:59:00     7
2011-01-16 19:58:00     8
2011-01-16 20:59:00     9`

fxts[.indexwday(fxts)==1]  #this gives you all the Mondays

for subsetting the time you use

fxts["T19:30/T20:00"] # this will give you the time period you are looking for

and here you combine weekday and time period

fxts["T18:30/T20:00"] & fxts[.indexwday(fxts)==1] # to get a logical vector or
fxts["T18:30/T21:00"][.indexwday(fxts["T18:30/T21:00"])==1] # to get the values

>                   value
2011-01-03 18:58:00     3
2011-01-10 18:59:00     6

Upvotes: 0

Related Questions