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 to do it...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.14.150