Vlad Skvortsov's Blog

Tags
cyrillic ditrack gtd guitar mac music pdf phd postscript productivity programming projects python r russian shell terminal tex tips utf-8 wadcomblog

My name is Vlad Skvortsov, I'm a software engineer: it's my job, hobby and addiction.

My primary interests include high-performance, scalable, fault-tolerant distributed systems; server-side applications; information retrieval technologies; procedural aspects of software engineering process.

I work on several private and open-source projects, hacking in Python, Haskell, Erlang, Perl and C.

Guitar, hiking, ice hockey and other hobbies help me to balance my life.

My e-mail is vss@73rus.com.

Fitting Quadratic Models In R

Jul 14 2008, 12:35 permalink
Tags: r tips

I 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:


> m = lm(y ~ x2 + x1, data = xs)

...and here we go:

> 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.