[R] using predict.lm() within a function

Michael Friendly friendly at yorku.ca
Mon Oct 24 23:30:12 CEST 2011


I've written a simple function to draw a regression line in a plot and 
annotate the line showing the slope
with a label.  It works, as I'm using it, when the horizontal variable 
is 'x', but gives incorrect results otherwise.
What's wrong?

# simple function to show the slope of a line
show.beta <- function(model, x="x", x1, x2, label, col="black", ...) {
     abline(model, col=col, lwd=2)
#    x <- deparse(substitute(x))      # doesn't help
     xs <- data.frame(x=c(x1, x2, x2))
     ys <- predict(model, xs)
     lines(cbind(xs,ys[c(1,1,2)]), col=col)
     text(x2, mean(ys[1:2]), label, col=col, ...)
}

x=rnorm(10)
DF <- data.frame(x, y=.25*x+rnorm(10))

# OK
with(DF, {
     plot(y ~ x)
     mod <- lm(y ~ x)
     show.beta(mod, "x", -0.5, 0, "b", pos=4)
     })

# not OK
xx=rnorm(10)
DF2 <- data.frame(xx, y=.25*x+rnorm(10))

with(DF2, {
     plot(y ~ xx)
     mod <- lm(y ~ xx)
     show.beta(mod, "xx", -0.5, 0, "b", pos=4)
     })

 From the latter, I get:

Warning message:
'newdata' had 3 rows but variable(s) found have 10 rows
 >



-- 
Michael Friendly     Email: friendly AT yorku DOT ca
Professor, Psychology Dept.
York University      Voice: 416 736-5115 x66249 Fax: 416 736-5814
4700 Keele Street    Web:   http://www.datavis.ca
Toronto, ONT  M3J 1P3 CANADA



More information about the R-help mailing list