Replace lm coefficients in [r]

泄露秘密 提交于 2021-02-07 04:26:01

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/15417680/replace-lm-coefficients-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!