non linear regression 'abline'

user1466195 picture user1466195 · Sep 26, 2012 · Viewed 12.3k times · Source

Still quite new to R (and statistics to be honest) and I have currently only used it for simple linear regression models. But now one of my data sets clearly shows a inverted U pattern. I think I have to do a quadratic regression analysis on this data, but I'm not sure how. What I tried so far is:

    independentvar2 <- independentvar^2
    regression <- lm(dependentvar ~ independentvar + independentvar2)
    summary (regression)
    plot (independentvar, dependentvar)
    abline (regression)

While this would work for a normal linear regression, it doesn't work for non-linear regressions. Can I even use the lm function since I thought that meant linear model?

Thanks Bert

Answer

Roman Luštrik picture Roman Luštrik · Sep 26, 2012

This example is from this SO post by @Tom Liptrot.

plot(speed ~ dist, data = cars)
fit1 = lm(speed ~ dist, cars) #fits a linear model
plot(speed ~ dist, data = cars)
abline(fit1) #puts line on plot
fit2 = lm(speed ~ I(dist^2) + dist, cars) #fits a model with a quadratic term
fit2line = predict(fit2, data.frame(dist = -10:130))

enter image description here