Re: [R] Cumsum in Lattice Panel Function

From: Deepayan Sarkar <deepayan.sarkar_at_gmail.com>
Date: Mon, 09 May 2011 00:20:36 +0530

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



R-help_at_r-project.org 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. Received on Sun 08 May 2011 - 18:53:07 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 11 May 2011 - 20:40:07 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive