[R] lattice xyplot with cumsum() function inside
Ivan Krylov
|kry|ov @end|ng |rom d|@root@org
Sun Sep 29 10:02:46 CEST 2024
В Sat, 28 Sep 2024 13:34:22 +0000
Naresh Gurbuxani <naresh_gurbuxani using 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
More information about the R-help
mailing list