2

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

user1466195
  • 51
  • 1
  • 1
  • 4
  • 2
    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 Sep 26 '12 at 08:16
  • 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. –  Sep 26 '12 at 08:17
  • @woodchips The specified model contains an intercept (default for `lm`). – Roland Sep 26 '12 at 08:19

1 Answers1

7

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

Community
  • 1
  • 1
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
  • 2
    +1 This is the canonical idiom with R's modelling functions. Use the `predict()` method on a sequential set of new data over the range of the covariates. (This obviously gets a little more complex when there are more than just a single covariate, e.g. partial effects.) – Gavin Simpson Sep 26 '12 at 08:37