Book Image

R Graphs Cookbook Second Edition

Book Image

R Graphs Cookbook Second Edition

Overview of this book

Table of Contents (22 chapters)
R Graphs Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Adding nonlinear model curves


In this recipe, we will learn how to fit and draw a nonlinear model curve to a dataset.

Getting ready

All you need for the next recipe is to type it at the R prompt as we will only use some base functions. You can also save the recipe code as a script so that you can use it again later on.

How to do it...

Plot an exponential plot:

x <- -(1:100)/10
y <- 100 + 10 * exp(x / 2) + rnorm(x)/10
nlmod <- nls(y ~  Const + A * exp(B * x), trace=TRUE)

plot(x,y)
lines(x, predict(nlmod), col="red")

How it works...

We first plot y against x, where x is a variable defined using the: sequence operator and y is an exponential function of x. Then, we fit a nonlinear model to the data using the nls() function. We save the model fit as nlmod and finally draw the model predicted values by passing x and predict(nlmod) to the lines() function.