I have a time series of returns. In the first column I have all my dates. With this function (searching for hours) I finally managed to get the first value of every month.
The problem was, that not always day 1 is the first value. Sometimes it is day 2,3,4,5 etc.
Luckily with this function it all works:
library(xts)
month<- data[,1] ## all my dates
first.values <- month[head(endpoints(month, "months") + 1, -1)]
What I want to understand though: Why the +1 and -1? That is all I would like to understand.
I am not satisfied that the code works, I really want to understand. Unfortunately I do not have enough reputation to contact or comment someone (since I found this code here).
Let's prepare sample data :
xts::endpointsgives the index of the last observation of each month, always beginning with 0:So if you add
1, you'll have the index of the first available day of the next month and conveniently, the 0 will be the index of the 1st day of the 1st month:The last value is meaningless though, so we drop it:
And we end up with your solution:
An alternate way of doing it: