3

I'm trying to predict an lm object using predict.lm. However, I would like to use manually inserted coefficients. To do this I tried:

model$coefficients <- coeff

(where "coeff" is a vector of correct coefficients) which would indeed modify the coefficients as I want. Nevertheless, when I execute

 predict.lm(model, new.data)

I just get predictions calculated with the "old" parameters. Is there a way I could force predict.lm to use the new ones?

Post Scriptum: I need to do this to fit a bin-smooth (also called regressogram). In addition, when I predict "by hand" (i.e. using matrix multiplication) the results are fine, hence I'm quite sure that the problem lies in the predict.lm not recognizing my new coefficients.

Thanks in advance for the help!

OnlyAL
  • 81
  • 9
  • 1
    Why do you insist on using `predict.lm` for this? It's not what it is designed for. – Roland Feb 16 '16 at 17:11
  • I would like to use it for two reasons: 1. Even if I already have all the data to plot a graph, I would like to make the code a little bit more elegant and 2. Because I need to use the modified lm object to create a k-fold cross validation function: the existing ones would (obliviously), estimate coefficients which are not the correct ones. – OnlyAL Feb 16 '16 at 17:30
  • @AlbertoFerrando Can you just do a matrix multiplication using the coefficients you are interested in ? Here is a link to another SO post that is a similar questions (possible duplicate): http://stackoverflow.com/questions/2062194/create-lm-object-from-data-coefficients – steveb Feb 16 '16 at 17:38
  • I did a matrix multiplication and it works. The issue is that I would like to fit my model using the ready-made R functions, given that I need to estimate the Generalization error. I would like to avoid to code the algorithm by myself. – OnlyAL Feb 16 '16 at 20:33

1 Answers1

2

Hacking the $coefficients element does indeed seem to work. Can you show what doesn't work for you?

dd <- data.frame(x=1:5,y=1:5)
m1 <- lm(y~x,dd)
m1$coefficients <- c(-2,1)
m1
## Call:
## lm(formula = y ~ x, data = dd)
## 
## Coefficients:
## [1]  -2   1

predict(m1,newdata=data.frame(x=7))  ## 5  = -2+1*7

predict.lm(...) gives the same results.

I would be very careful with this approach, checking each time you do something different with the hacked model.

In general it would be nice if predict and simulate methods took a newparams argument, but they don't in general ...

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • It turned out to be a scoping problem: after I eliminated all the variables and re-run the code, the suggested solution worked indeed. – OnlyAL Feb 18 '16 at 15:52