create function from formula and regression coefficients
Question
Using R, I wrote a function for exploratory data analysis that produces a scatterplot and fits a regression line using lm. The formula is not fixed. Works perfectly, and I get back the optimized formula (my.results <- lm(fml, data); my.results$model
) and the coefficients (my.results$coefficients
). Now I want to proceed and obtain a function, e.g. for finding the zeros (i.e. where the function crosses the x axis, etc.). Doing this "manually" for a given lm
result is obviously trivial. But is there a way to construct this function from the lm
results (without knowing the structure of the formula in advance)? Thanks for any suggestions!
Solution
An example:
set.seed(42)
x <- 1:100
y <- (x-2)*(x-15)*(x-90) + rnorm(100)
fit <- lm(y~poly(x, degree=3, raw=TRUE))
If your fit is a polynomial, you can find all roots quite easily:
polyroot(coef(fit))
#[1] 1.999364-0i 15.000010-0i 89.999991+0i
If it is an arbitrary function, which is linear in its coefficients, you can find roots numerically:
invLm <- function(x, mod.lm) predict(mod.lm, newdata=list(x=x))
uniroot(invLm, c(-100, 100), mod.lm=fit)
#$root
#[1] 89.99999
OTHER TIPS
Here is an option that will figure out the name(s) of the predictor(s) in the fit and create a function (that uses predict) to calculate the predicted values. You need to make sure to pass the correct number of variables in the correct order (if there is only 1 predictor then this does not matter):
genFun1 <- function(model) {
xvname <- all.vars( delete.response( terms( model ) ) )
function(...) {
newdat <- data.frame(...)
names(newdat) <- xvname
predict(model, newdat)
}
}
x <- 1:10
y <- 2*x - 5 + rnorm(10)
fit1 <- lm( y ~ x )
fit2 <- lm( y ~ sqrt(x) + I(x^3) )
len <- x
adjmas <- y
fit3 <- lm( adjmas ~ len )
pred1 <- genFun1(fit1)
pred2 <- genFun1(fit2)
pred3 <- genFun1(fit3)
plot(x,y)
xx <- seq(0,10, length.out=25)
lines( xx, pred1(xx), col='red' )
lines( xx, pred2(xx), col='green' )
lines( xx, pred3(xx), col='blue')