Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

5. Scatter Plots > Adding Fitted Lines from Multiple Existing Models

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(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:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint