Replace the coefficients lm in [r]

Is it possible to replace the coefficients in the object lm?

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 help would be greatly appreciated.

0
source share
1 answer

Your code does not play because there are several errors in your code. Here's a fixed version that also shows your error:

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 what you used fit$coef, although the component name in the lmoutput is valid coefficients. The shortened version works to get values, but not to install, because it created a new component with the name coef, and the function coefretrieved the values fit$coefficient.

+2
source

All Articles