[R] Cumsum in Lattice Panel Function

Elliot Joel Bernstein elliot.bernstein at fdopartners.com
Wed May 11 22:27:49 CEST 2011


That worked perfectly. Thanks!

- Elliot

On Mon, May 09, 2011 at 12:20:36AM +0530, Deepayan Sarkar wrote:
> On Fri, May 6, 2011 at 9:24 PM, Elliot Joel Bernstein
> <elliot.bernstein at fdopartners.com> wrote:
> > I'm trying to create an xyplot with a "groups" argument where the y-variable
> > is the cumsum of the values stored in the input data frame. I almost have
> > it, but I can't get it to automatically adjust the y-axis scale. How do I
> > get the y-axis to automatically scale as it would have if the cumsum values
> > had been stored in the data frame?
> >
> > Here is the code I have so far:
> >
> > require(lattice)
> >
> >
> >
> > dates <- seq(as.Date("2011-01-01"), as.Date("2011-04-30"), "days")
> > g <- 1:3
> >
> >
> > dat <- data.frame(date = rep(dates, length(g)),
> >                  group = rep(g, each = length(dates)),
> >                  value = rnorm(length(dates)*length(g)) + 0.05)
> >
> >
> > xyplot(value ~ date, data = dat, group = group, type = 'l', grid = TRUE,
> >       panel = panel.superpose,
> >       panel.groups = function(x, y, ...) { panel.xyplot(x, cumsum(y), ...)
> > })
> >
> >
> > I want the result to look the same as if I had done
> >
> > dat$cumvalue <- with(dat, unsplit(lapply(split(value, group), cumsum),
> > group))
> > xyplot(cumvalue ~ date, data = dat, group = group, type = 'l', grid = TRUE)
> 
> You need something along the lines of
> 
> xyplot(value ~ date, data = dat, group = group, type = 'l', grid = TRUE,
>        panel = panel.superpose,
>        panel.groups = function(x, y, ...) {
>            panel.xyplot(x, cumsum(y), ...)
>        },
>        prepanel = function(x, y, groups, ...) {
>            yy <- unlist(tapply(y, groups, cumsum))
>            list(ylim = range(yy, finite = TRUE))
>        })
> 
> -Deepayan

-- 
Elliot Joel Bernstein, Ph.D. | Research Associate | FDO Partners, LLC
134 Mount Auburn Street | Cambridge, MA | 02138
Phone: (617) 503-4619 | Email: elliot.bernstein at fdopartners.com



More information about the R-help mailing list