[R] lattice xyplot with cumsum() function inside

Ivan Krylov
Sun, 29 Sep 2024 08:02:46 -0000

? Sat, 28 Sep 2024 13:34:22 +0000
Naresh Gurbuxani <naresh_gurbuxani at hotmail.com> ?????:

> mydt[, lapply(.SD, sum), by = .(xgroup), .SDcols = c("x")]
> #   xgroup        x
> #   <char>    <num>
> #1:      A 26.00455
> #2:      B 71.55405
>
> #For xgroup = "B", line starts at the sum of all previous x
values
> including xgroup = "A"
> #Intended result is to separate cumsum(x) for groups "A" and
"B"
> mydt[, xyplot(cumsum(x) ~ date, groups = xgroup, type = c("l",
"g"))]

> Is this a bug or incorrect use of function?

Thank you very much for providing a reproducible example! Lattice first
evaluates the formula and only then splits the results into groups.
This is a consequence of the design where grouping is handled by the
panel functions such as panel.superpose.

I think you can obtain the desired result by letting data.table group
the rows:

xyplot(
 x ~ date, groups = xgroup, type = c("l", "g"),
 data = mydt[,
  c(list(date=date), lapply(.SD, cumsum)),
  by = xgroup, .SDcols = 'x'
 ]
)

A more idiomatic solution might be:

mydt[,xsum := cumsum(x), by = xgroup]
xyplot(xsum ~ date, groups = xgroup, type = c("l", "g"),
data = mydt)

--
Best regards,
Ivan