[R] fitting with lm

Kaspar Pflugshaupt pflugshaupt at geobot.umnw.ethz.ch
Tue Mar 19 18:05:31 CET 2002

On 19.3.2002 17:03 Uhr, Arne Mueller wrote:

> Dear All,
> I'm getting confused with the concept R uses to do regression using lm.
> I'm afmiliar with gnuplot and the build-in fit command, but couldn't get
> R's lm to work on my data.
> I know that my data follows a powerlaw or maybe an exponential function,
> and I'd like to determine the best fitting factors for the formula:
> a*x^b where b < 0.
> I've tried thge follwoing:
> s <- lm(y ~ x)


> What has R done? I assume the formula is just a+b*x and I can get a and
> b via
>> coef(s)
> (Intercept)           x
> 21.20917074 -0.06560878
> But:
>> s <- lm(y ~ a*x^b)
> Error in terms.formula(formula, data = data) :
>       invalid power in formula
> I went through the formula section of the R-manual, but I realy don't
> get it.

Generally, you want to look at the nlm library to fit complicated functions
to your data. lm() does just linear models. In your case, however, you could
try a log-transformation to linearize (fitting log(y) ~ a + log(x) * b),
then re-transform the coefficients to the original scale.

> Finally, I'd like to have the raw data-points together with a line
> representing the function used to fit the data in a plot? How can I plot
> function, e.g. sin(x) ?

Look at help(curve). To add the results of any fit to an existing data
scatterplot, you can also use
lines(x.values, predict(your.model))

- if your x values are sorted by size. If not, use something like this:
x.order <- order(x.values)
lines(x.values[x.order], predict(your.model)[x.order])

> I hope I just need a primer on this to get going.

Hope that helps.

Kapsar Pflugshaupt


Kaspar Pflugshaupt
Geobotanisches Institut
Zuerichbergstr. 38
CH-8044 Zuerich

Tel. ++41 1 632 43 19
Fax  ++41 1 632 12 15

mailto:pflugshaupt at geobot.umnw.ethz.ch
privat:pflugshaupt at mails.ch

r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list