Re: [R] Controlling the length of line with abline(lm())

From: Rolf Turner <r.turner_at_auckland.ac.nz>
Date: Thu, 19 Jun 2008 17:01:50 +1200

On 19/06/2008, at 2:09 PM, Tariq Perwez wrote:

> Hi
> I just realized that when I use linear regression to draw a line
> through my
> data points with something like the following:
>
> abline(lm(y ~ x))
>
>
> the length of the line is infinite, i.e., the line goes beyond the
> smallest
> and the largest data values. This seems not very right to me (not
> to mention
> it looks unaesthetic). I do not mean to imply that the straight-line
> behavior of my system is maintained throughout. I would like to
> limit the
> length of this line to the range of my data. However, I have not
> been able
> to figure out how to. Very disconcertingly, I found out that all
> the books
> that teach statistics using R seem to be drawing such infinite
> length-lines.
> I would appreciate any advice or suggestions.

As things stand, I don't think you can do it in one hit. You have to go through something like

	fit <- lm(y~x)
	z <- predict(fit,data.frame(x=range(x)))
	lines(range(x),z)

I guess one could ``automate'' this via something like:

	fline <- function(object) {
	# ``fline'' <--> fitted line.
		r <- range(object$model[,2])
		d <- data.frame(r)
		names(d) <- attr(object$terms,"term.labels")
		y <- predict(object,d)
		lines(r,y)
	}

(There may well be a cleverer way to do this .....)

And then execute

        fline(lm(y~x))

Howzat?

                cheers,

                        Rolf Turner                 

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 19 Jun 2008 - 05:16:41 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 19 Jun 2008 - 05:30:44 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive