This does what you want, I think.
The basic idea is to detect transitions from 1 (recession) to 0 (no recession) and vice versa. We can do this with diff(...)
. diff(...)
returns the vector containing the difference between a given row and the previous one, for all rows (the first element is NA
). So, when we go into a recession diff returns 1, when we leave a recession, diff returns -1. All other times it returns 0.
library(quantmod)
getSymbols("USREC",src="FRED")
getSymbols("UNRATE", src="FRED")
unrate.df <- data.frame(date= index(UNRATE),UNRATE$UNRATE)
start <- index(USREC[which(diff(USREC$USREC)==1)])
end <- index(USREC[which(diff(USREC$USREC)==-1)-1])
reccesion.df <- data.frame(start=start, end=end[-1])
recession.df <- subset(reccesion.df, start >= min(unrate.df$date))
ggplot()+
geom_line(data=unrate.df, aes(x=date,y=UNRATE)) +
geom_rect(data=recession.df,
aes(xmin=start,xmax=end, ymin=0,ymax=max(unrate.df$UNRATE)),
fill="red", alpha=0.2)
EDIT (Response to OP's comment)
library(PerformanceAnalytics)
cycles.dates <- paste(format(start,"%Y-%m"),format(end[-1],"%Y-%m"),sep="/")
chart.TimeSeries(UNRATE,period.areas=cycles.dates,
period.color="lightblue", lwd=1)