[R] Month end calculations

Gabor Grothendieck ggrothendieck at gmail.com
Thu Aug 30 20:14:49 CEST 2007


And one more yearmon solution.  Here z is a zoo series as before:

tt <- time(z)
aggregate(z, ave(tt, as.yearmon(tt), FUN = max), tail, 1)


On 8/30/07, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
> The last line is wrong (see below for correction):
>
> On 8/30/07, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
> > The zoo package includes the "yearmon" class to facilitate such
> > manipulations.  Here are a few solutions assuming you store
> > you series in a zoo variable:
> >
> > # test data
> > library(zoo)
> > z <- zoo(1001:1100, as.Date(101:200))[-(45:55)]
> >
> > # Solution 1.  tapply produces indexes of last of month
> > tt <- time(z)
> > z[ c(tapply(seq_along(tt), as.yearmon(tt), tail, 1)) ]
> >
> > # If we want to create a last variable which corresponds
> > # to last in sas then do it this slightly longer way:
> >
> > # Solution 2
> > tt <- time(z)
> > last <- seq_along(tt) %in% tapply(seq_along(tt), as.yearmon(tt), tail, 1)
> > z[last]
> >
> > # Solution 3. another solution with a last variable.  f(x) is
> > # vector same length as x with all 0's except last element is 1.
> > tt <- time(z)
> > f <- function(x) replace(0*x, length(x), 1)
> > last <- ave(seq_along(tt), as.yearmon(tt), FUN = f)
> > z[last]
>
> This last line should be:
>
> z[last == 1]
>
>
> >
> > In all these solutions the last point in the series is always
> > included.
> >
> > We have not assumed that every day is necessarily included in your
> > series but if every day is included then even simpler solutions
> > are possible.
> >
> > On 8/29/07, Shubha Vishwanath Karanth <shubhak at ambaresearch.com> wrote:
> > > Hi R users,
> > >
> > >
> > >
> > > Is there a function in R, which does some calculation only for the month
> > > end in a daily data?... In other words, is there a command in R,
> > > equivalent to "last." function in SAS?
> > >
> > >
> > >
> > > BR, Shubha
> > >
> > >
> > >        [[alternative HTML version deleted]]
> > >
> > > ______________________________________________
> > > R-help at stat.math.ethz.ch mailing list
> > > https://stat.ethz.ch/mailman/listinfo/r-help
> > > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> > > and provide commented, minimal, self-contained, reproducible code.
> > >
> >
>



More information about the R-help mailing list