Graphics Reference
In-Depth Information
Adding Fitted Lines from Multiple Existing Models
Problem
You have already created a fitted regression model object for a data set, and you want to plot the
lines for that model.
Solution
Use the
predictvals()
function from the previous recipe along with
dlply()
and
ldply()
from the plyr package.
With the
heightweight
data set, we'll make a linear model with
lm()
for each of the levels
of
sex
, and put those model objects in a list. The model building is done with a function,
make_model()
, defined here. If you pass it a data frame, it simply returns an
lm
object. The
model can be customized for your data:
make_model
<-
function
function
(data) {
lm(heightIn ~ ageYear, data)
}
With this function, we can use the
dlply()
function to build a model for each subset of
data. This will split the data frame into subsets by the grouping variable
sex
, and apply
make_model()
to each subset. In this case, the
heightweight
data will be split into two data
frames, one for males and one for females, and
make_model()
will be run on each subset. With
dlply()
, the models are put into a list and the list is returned:
library(gcookbook)
# For the data set
library(plyr)
models
<-
dlply(heightweight,
"sex"
,
.
fun
=
make_model)
# Print out the list of two lm objects, f and m
models
$f
Call:
lm(formula
=
heightIn ~ ageYear, data
=
data)
Coefficients:
(Intercept)
ageYear
43.963
1.209
$m