# Re: [R] Forcing best-fit lines to go through the origin

From: Henric Nilsson <henric.nilsson_at_statisticon.se>
Date: Mon 18 Apr 2005 - 16:04:12 EST

Jim Milks said the following on 2005-04-18 03:08:

> Dear All,
>
> I have a rather unusual problem. I have a set of data for a class in
> subsurface processes. From that dataset, I must calculate the slope of
> the best-fit line (which is the parameter of interest). The problem I
> have is twofold: 1) for the purposes of the exercise, I must force my
> best-fit line to go through the origin (0,0), and 2) the line must be
> linear, even though the data is not. I would like to use R to help me
> calculate the line, but am unaware of any code or packages that will
> allow me to force the line through the origin.
>
> The dataset is as follows:
>
> C C*
> 4.1 17.4
> 6.2 24.9
> 27.9 39.5
> 91.1 57.4
> 168.0 75.5

Depending on your definition of `best-fit', you may use the `lm' function where `best-fit' corresponds to solving a least-squares problem. Try ?lm at the R prompt.

Not that I know if you want to regress C on C*, or the other way around.. Let's do both:

C C.

```1   4.1 17.4
2   6.2 24.9
3  27.9 39.5
4  91.1 57.4
5 168.0 75.5
```

> fit1 <- lm(C ~ C. -1 , data = dta)
> coef(fit1)

C.
1.676325
> fit2 <- lm(C. ~ C -1, data = dta)
> coef(fit2)

C
0.5150568

To convince yourself, take a look at the data with the least-squares line superimposed:

> plot(C ~ C., data = dta, xlim = c(0, 200), ylim = c(0, 100))  > abline(fit1)

Plotting `fit2' is left as an exercise... ;-)

HTH,
Henric

>
> Thank you in advance for any advice you can give me.
>
> Sincerely,
>
> Jim Milks
> Environmental Sciences Ph.D. Program
> Wright State University
> 3640 Colonel Glenn Hwy
> Dayton, OH 45435
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help