[R] lattice densityplot with weights

Naresh Gurbuxani n@re@h_gurbux@n| @end|ng |rom hotm@||@com
Fri Sep 29 12:32:20 CEST 2023


density() function in R accepts weights as an input.  Using this
function, one can calculate density and plot it.  Is it possible to
combined these two operations in lattice densityplot()?

mydf <- data.frame(name = "A", x = seq(-2.9, 2.9, by = 0.2), wt =
diff(pnorm(seq(-3, 3, by = 0.2))))
mydf <- rbind(mydf, data.frame(name = "B", x = mydf$x + 0.5, wt =
mydf$wt))
with(subset(mydf, name == "A"), density(x, weights = wt / sum(wt)) |>
plot(xlim = c(-3, 3.5), xlab = "", main = "Density Plots"))
with(subset(mydf, name == "B"), density(x, weights = wt / sum(wt)) |>
lines(lty = 2, col = 2))
grid()
legend("topright", legend = c("A", "B"), col = c(1, 2), lty = c(1, 2),
bty = "n")

# I want to do something like this:
# densityplot(~ x, weights = wt, groups = name, data = mydf, type = c("l", "g"))



More information about the R-help mailing list