Imagine that your data are dates in a standard format [YEAR-MONTH-DAY (as in 2011-23-04) is one such format] and you want a vector of the dates that are the first day in the month of your data set. You might, for example, be interested in this (as an intermediate calculation) because you wish to match some S&P 500 returns data to monthly data. Frustratingly, the S&P 500 returns data do not report on the weekends or on holidays when the exchange is closed.
Here's a function that will do return a vector of first-days-of-the-month if you give it a vector of dates. Maybe you will find this useful.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## --------------------------- ## | |
## Function takes a vector of ## | |
## dates as its input. ## | |
## ## | |
## It produces a vector of ## | |
## dates that are the first ## | |
## in their respective months ## | |
## --------------------------- ## | |
firstDayMonth=function(x) | |
{ | |
x=as.Date(as.character(x)) | |
day = format(x,format="%d") | |
monthYr = format(x,format="%Y-%m") | |
y = tapply(day,monthYr, min) | |
first=as.Date(paste(row.names(y),y,sep="-")) | |
as.factor(first) | |
} |
Enjoy!
Thank you, tony. I am trying to match CRSP and compustat data as we speak. I hope this will be helpful. Do you have any more tips that may help (an old post, website you could link me to)? Thanks
ReplyDeleteBefore this post, I hadn't done anything on this blog about merging data. In the next couple of days, my plan is to post something on merging data frames in R. My application will be with the FRED data, but perhaps, you'll find it useful.
ReplyDelete