[R] modifying model coefficients

Chuck Cleland ccleland at optonline.net
Mon Oct 19 15:31:15 CEST 2009


On 10/18/2009 11:26 PM, tdm wrote:
> I have build a model but want to then manipulate the coefficients in some
> way.
> 
> I can extract the coefficients and do the changes I need, but how do I then
> put these new coefficients back in the model so I can use the predict
> function? 
> 
> my_model <- lm(x ~ . , data=my_data)
> my_scores <- predict(my_model, my_data)
> 
> my_coeffs <- coef(my_model)
> 
> ## here we manipulate my_coeffs
> ## and then want to set the my_model 
> ## coefficients to the new values so we 
> ## predict using the new values
> 
> my_model.coefs <- my_coeffs ?? how is this done?
> 
> ?? so that this will work with the new coefficients
> my_scores_new <- predict(my_model, my_data)
> 
> Any code snippets would be appreciated very much.

  Have you considered setting the coefficients to the values in
my_coeffs using offset()?

fm1 <- lm(Sepal.Length ~ offset(0.90*Sepal.Width) +
                         offset(0.50*Petal.Length) +
                         offset(-0.50*Petal.Width),
                         data = iris)

summary(fm1)

predict(fm1)

all.equal(as.vector(predict(fm1)),
          c(as.matrix(cbind(1, iris[,2:4])) %*%
          c(1.8124, 0.9, 0.5, -0.5)))

[1] TRUE

?offset

-- 
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894




More information about the R-help mailing list