2

Is it possible to replace coefficients in lm object?

I thought the following would work

# sample data 
set.seed(2157010)
x1 <- 1998:2011
x2 <- x1 + rnorm(length(x1))
y <- 3*x1 + rnorm(length(x1))
fit <- lm( y ~ x1 + x2)

# view origional coefficeints
coef(fit)

# replace coefficent with new values
fit$coef(fit$coef[2:3]) <- c(5, 1)

# view new coefficents
coef(fit)

Any assistance would be greatly appreciated

MikeTP
  • 7,716
  • 16
  • 44
  • 57
  • I'm very curious Why someone would want to do this. – ndoogan Mar 14 '13 at 18:52
  • Me too, my first though was also "Why??" – Jouni Helske Mar 14 '13 at 18:55
  • In my case, I am looping through linear models by region and some of my regions do not have the same number of explanatory variables as other regions. In these case, the lm returns NA for the model coefficient and I want to replace it with zero, as other downstream elements of my code depend on a numeric value in each explanatory variables slot. – MikeTP Mar 14 '13 at 18:59
  • @MikeTP Now I see, I wrote one solution for your related question also. – Jouni Helske Mar 14 '13 at 20:25
  • yes, and I appreciate both responses – MikeTP Mar 14 '13 at 21:19

1 Answers1

3

Your code is not reproducible, as there's few errors in your code. Here's corrected version which shows also your mistake:

set.seed(2157010) #forgot set.
x1 <- 1998:2011
x2 <- x1 + rnorm(length(x1))
y <- 3*x2 + rnorm(length(x1)) #you had x, not x1 or x2
fit <- lm( y ~ x1 + x2)

# view original coefficients
coef(fit)
 (Intercept)           x1           x2 
260.55645444  -0.04276353   2.91272272 

# replace coefficients with new values, use whole name which is coefficients:
fit$coefficients[2:3] <- c(5, 1)

# view new coefficents
coef(fit)
(Intercept)          x1          x2 
260.5565      5.0000      1.0000 

So the problem was that you were using fit$coef, although the name of the component in lm output is really coefficients. The abbreviated version works for getting the values, but not for setting, as it made new component named coef, and the coef function extracted the values of fit$coefficient.

Jouni Helske
  • 6,427
  • 29
  • 52