## Fitting Quadratic Models In R

Jul 14 2008, 12:35 permalinkI guess it's fairly obvious to statistics gurus, but I've spent quite some time trying to figure out how to fit a quadratic model (with linear coefficients) in R. Here's how.

So let's say we have this kind of data:

`> x = 1:100 > y = 0.5 * x * x - 15 * x + 3`

The trick is that we need separate variables containing both squared and plain values of x. I prefer to put them in a data frame:

`> xs = data.frame(x2 = x * x, x1 = x)`

Now all we have to to is call `lm()`

as in case with simple linear
model, but pass it appropriate formula and the data frame we created:

...and here we go:`> m = lm(y ~ x2 + x1, data = xs)`

`> m Call: lm(formula = y ~ x2 + x1, data = xs) Coefficients: (Intercept) x2 x1 3.0 0.5 -15.0`

Now, I'm not yet sure I understand why the formula here is x2 + x1; per the documentation it means "combine x2 with all x1 and remove the duplicates". I can't see how it applies here, but anyways. Hope this helps some statistics/R newbies.