# NOT RUN {
require('datasets')
# prediction from several angles
m <- lm(Sepal.Length ~ Sepal.Width, data = iris)
cplot(m)
# more complex model
m <- lm(Sepal.Length ~ Sepal.Width * Petal.Width * I(Petal.Width ^ 2),
data = head(iris, 50))
## marginal effect of 'Petal.Width' across 'Petal.Width'
cplot(m, x = "Petal.Width", what = "effect", n = 10)
# factor independent variables
mtcars[["am"]] <- factor(mtcars[["am"]])
m <- lm(mpg ~ am * wt, data = mtcars)
## predicted values for each factor level
cplot(m, x = "am")
## marginal effect of each factor level across numeric variable
cplot(m, x = "wt", dx = "am", what = "effect")
# marginal effect of 'Petal.Width' across 'Sepal.Width'
## without drawing the plot
## this might be useful for using, e.g., ggplot2 for plotting
tmp <- cplot(m, x = "Sepal.Width", dx = "Petal.Width",
what = "effect", n = 10, draw = FALSE)
if (require("ggplot2")) {
# use ggplot2 instead of base graphics
ggplot(tmp, aes(x = Petal.Width, y = "effect")) +
geom_line(lwd = 2) +
geom_line(aes(y = effect + 1.96*se.effect)) +
geom_line(aes(y = effect - 1.96*se.effect))
}
# a non-linear model
m <- glm(am ~ wt*drat, data = mtcars, family = binomial)
cplot(m, x = "wt") # prediction
# effects on linear predictor and outcome
cplot(m, x = "drat", dx = "wt", what = "effect", type = "link")
cplot(m, x = "drat", dx = "wt", what = "effect", type = "response")
# plot conditional predictions across a third factor
local({
iris$long <- rbinom(nrow(iris), 1, 0.6)
x <- glm(long ~ Sepal.Width*Species, data = iris)
cplot(x, x = "Sepal.Width", data = iris[iris$Species == "setosa", ],
ylim = c(0,1), col = "red", se.fill = rgb(1,0,0,.5), xlim = c(2,4.5))
cplot(x, x = "Sepal.Width", data = iris[iris$Species == "versicolor", ],
draw = "add", col = "blue", se.fill = rgb(0,1,0,.5))
cplot(x, x = "Sepal.Width", data = iris[iris$Species == "virginica", ],
draw = "add", col = "green", se.fill = rgb(0,0,1,.5))
})
# ordinal outcome
if (require("MASS")) {
# x is a factor variable
house.plr <- polr(Sat ~ Infl + Type + Cont, weights = Freq,
data = housing)
## predicted probabilities
cplot(house.plr)
## cumulative predicted probabilities
cplot(house.plr, what = "stacked")
## ggplot2 example
if (require("ggplot2")) {
ggplot(cplot(house.plr), aes(x = xvals, y = yvals, group = level)) +
geom_line(aes(color = level))
}
# x is continuous
cyl.plr <- polr(factor(cyl) ~ wt, data = mtcars)
cplot(cyl.plr, col = c("red", "purple", "blue"), what = "stacked")
cplot(cyl.plr, what = "class")
}
# }
Run the code above in your browser using DataLab