[R] lattice subscripts with both condition and group
Naresh Gurbuxani
n@re@h_gurbux@n| @end|ng |rom hotm@||@com
Tue Nov 5 13:26:07 CET 2024
How can I use subscripts to draw the last graph with one call to
function xyplot()?
Thanks,
Naresh
library(data.table)
library(lattice)
library(latticeExtra)
mydt2024 <- data.table(
date = rep(as.Date(c("2024-11-01", "2024-11-04")), c(8, 8)),
day_forward = rep(1:8, 2),
news_clicks = c(10, 12, 13, 18, 20, 21, 15, 11, 21, 23, 25, 18, 14, 12,
12, 10),
days_to_election = rep(c(4, 1), c(8, 8)),
electyear = "Election 2024")
## Works when only condition is present
mydt2024[
, xyplot(news_clicks ~ day_forward | date, type = c("l", "g"),
panel = function(x, y, ..., subscripts) {
panel.xyplot(x, y, ...)
panel.abline(v = days_to_election[subscripts][1], lty = 2)
})
]
mydt2020 <- data.table(
date = rep(as.Date(c("2020-10-30", "2020-11-02")), c(8, 8)),
day_forward = rep(1:8, 2),
news_clicks = c(9, 11, 12, 17, 21, 20, 14, 8, 20, 24, 28, 15, 12, 10,
8, 6),
days_to_election = rep(c(4, 1), c(8, 8)),
electyear = "Election 2020"
)
mydt <- rbind(mydt2020, mydt2024)
mydt[, `:=`(electlabel = paste(days_to_election, "Days Before"))]
## This does not work with both condition and group
mydt[
, xyplot(news_clicks ~ day_forward | electlabel, groups = electyear,
type = c("o", "g"), auto.key = list(columns = 2, space = "bottom"),
panel = function(x, y, ..., subscripts) {
panel.xyplot(x, y, ...)
panel.abline(v = days_to_election[subscripts][1], lty = 2)
})
]
## This works
electplot <- mydt[
, xyplot(news_clicks ~ day_forward | electlabel, groups = electyear,
type = c("o", "g"), auto.key = list(columns = 2, space = "bottom"))
]
vlineplot <- mydt[
, xyplot(news_clicks ~ day_forward | electlabel,
panel = function(x, y, ..., subscripts) {
panel.abline(v = days_to_election[subscripts][1], lty = 2)
})
]
electplot + vlineplot
More information about the R-help
mailing list