1

I am doing a multi-period analysis and I need to extract values between two dates from an xts object named data.

The start and end of my calculation lies between those dates. These same dates are used as rownames in a data.frame named results.

start_date <- head(rownames(results), n=1)
end_date <- tail(rownames(results), n=1) 

I also identify the column names with this vector:

> col_names
[1] "Stock1" "Stock2" "Stock3" 

I need to extract the observations in the data object in the columns in col_names and between start_date and end_date.

1
  • these variables are yielded from a data frame coming from other calculations. the code i have seems to work just fine. They are both character vectors containing the end and start date Commented Oct 17, 2015 at 14:18

1 Answer 1

1

Assuming that the 'start_date' and 'end_date' are 'character' vectors in the 'Date' format ('%Y-%m-%d'), we paste them together with sep='/', use that as row index, specify 'col_names' as column index and subset the xts object 'data'.

data[paste(start_date, end_date, sep="/"), col_names]

As a reproducible example

library(xts)
data(sample.xts)
start_date <- '2007-01-02'
end_date <- '2007-01-05' 
col_names <-  c('Open', 'High')
sample.xts[paste(start_date, end_date, sep="/"), col_names]
#               Open     High
#2007-01-02 50.03978 50.11778
#2007-01-03 50.23050 50.42188
#2007-01-04 50.42096 50.42096
#2007-01-05 50.37347 50.37347

If we need the rows which are between the 'start_date' and 'end_date'

sample.xts[index(sample.xts) > start_date &
            index(sample.xts) < end_date, col_names]
#               Open     High
#2007-01-03 50.23050 50.42188
#2007-01-04 50.42096 50.42096
Sign up to request clarification or add additional context in comments.

7 Comments

thats perfect, this is very helpful. is there a way to change the period within that that function? i tried using start_date + 5 and end_date + 5 so that it uses a the period 5 days ahead of the start_date and end but it didn't work.
@AlexBădoi Try as.Date(start_date)+5. For the example dataset, sample.xts[paste(as.Date(start_date)+5, as.Date(end_date)+5, sep='/'), col_names] worked
@AlexBădoi Yes, you are right it includes all calendar days. One option would be to subset the days using is.weekend. I guess this link helps you in doing that.
@AlexBădoi As I mentioned earlier, my solution was based on your earlier description. If you had correctly mentioned the problem earlier, it would have saved both of our time. Now, it is totally different and should be a new question. Otherwise, people update n number of times and the answerer has to answer each time the question gets updated.
got it. i will post a new question about it.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.