[R] sample nth day data in each month

Gabor Grothendieck ggrothendieck at gmail.com
Thu Nov 15 19:53:09 CET 2007


On Nov 15, 2007 12:54 PM, Carles Fan <eexchange at gmail.com> wrote:
> Dear all
>
> i have a time series containing trading dates and historical stock prices:
> Date             Price
> 10-Jan-2007  100
> 11-Jan-2007  101
> 13-Jan-2007  99
> ......
> ......
> ......
> 10-Nov-2007  200
>
> i want to sample every 21st data of each month:
> 21-Jan-2007 101
> 21-Feb-2007 111
> 21-Mar-2007 131
> ......
> ......
> ......
> 21-Oct-2007 140
>
> 1) how can i do that?
> 2) if some of the dates are non-trading day, how can i tell "R" to use
> "modified following" or "following" data?


Using zoo, z is some test data.  zz is only those points whose day
of the month is 21 or more.  In the last line we keep only the first
point in each month in zz.

library(zoo)
z <- zoo(101:200, as.Date("2000-01-01") + seq(0, len = 100, by = 2))

zz <- z[as.numeric(format(time(z), "%d")) >= 21]
zz[!duplicated(as.yearmon(time(zz)))]



More information about the R-help mailing list