Get the 4th Wednesday of each November in R

r

Solution

Use .indexmon etc to access the POSIXlt values directly

GSPC[.indexmon(GSPC)==10 & .indexmday(GSPC) > 22 & .indexmday(GSPC) < 29
       &.indexwday(GSPC) == 3]

           GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted
2007-11-28   1432.95   1471.62  1432.95    1469.02  4508020000       1469.02
2008-11-26    852.90    887.68   841.37     887.68  5793260000        887.68
2009-11-25   1106.49   1111.18  1104.75    1110.63  3036350000       1110.63
2010-11-24   1183.70   1198.62  1183.70    1198.35  3384250000       1198.35
2011-11-23   1187.48   1187.48  1161.79    1161.79  3798940000       1161.79

Problem

I have a time-indexed matrix (xts object) and I want only the fourth Wednesday of every November. ``` require(quantmod) getSymbols("^GSPC", from="1900-01-01") #returns GSPC GSPC$WED <- weekdays(time(GSPC)) == "Wednesday" GSPC$NOV <- months(time(GSPC)) == "November" G <- GSPC[GSPC$WED==1 & GSPC$NOV==1] ``` That's as far as I got in R. To solve my problem I punted up to bash. ``` write.zoo(G, "wen_in_nov") ``` I did the following hack: ``` cat wen_in_nov | grep -v IND | cut -c 1-10 | sed 's/-/ /g' | awk '{if($3 >= 22 && $3 < 29) print $1, $2, $3, "winner"}' | sed 's/ /-/g' > fourth_wen ``` The `fourth_wen` file needs to separate the `-` from the string 'winner' so I just did that in vi. Importing into back to R: ``` fourth_wen <- read.zoo("fourth_wen", format="%Y-%m-%d") ``` And that essentially is the fourth Wednesday in November since 1950. Is there a way to do it all in R with less code?

Original source