Search code examples
rplotnon-linear-regression

Better way call a non-linear regression model in curve() drawings in R?


I have been learning how to plot graphs and curves in R, and have used the plot() and curve() functions with a set of data to plot both the data and the curve. However, I don't believe I am using the most efficient methods.

What I have done is set up 2 vectors from a data.frame that and then I assigned an object (call it o) to the nls() function like o<-nls(y~I(a*x^3)+I(b*x^2)+I(c*x)+d). I could get all of the coefficient values for o (a,b,c,d) by calling o. I can then plug approximations for those values into the curve() function after plotting the points. That works, but I was wondering if there is any way to plug o directly into the curve function so I don't have to retype each coefficient?


Solution

  • Note that your function is a polynomial and therefore linear in its coefficients. Anyway, it works the same with nls as with lm. Specify the data.frame for the fit:

    o <- lm(y ~ poly(x, 3, raw = TRUE), data = DF)
    plot(y ~ x, data = DF)
    curve(predict(o, newdata = data.frame(x = x)), add = TRUE)