In this recipe, we will learn how to fit and draw a nonlinear model curve to a dataset.
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.
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")
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.
3.144.117.167