2
votes

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

1
Linear model means linear in the parameters and not (necessarily) linear in the variables. A polynom is a linear model. However, abline only plots a straight line, which is obviously not possible with a quadratic function. Look at ?curve instead. If you do a Google search you should find example code easily. - Roland
Why use a nonlinear regression to solve a linear regression problem? Besides, it looks like you have no constant term in the model, as well as other issues. - user85109
@woodchips The specified model contains an intercept (default for lm). - Roland

1 Answers

7
votes

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