2013-03-14 38 views
0

是否可以替换lm对象中的系数?替换[r]中的lm系数

我以为以下会工作

# 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) 

任何援助将不胜感激

+0

我很好奇为什么有人会想这样做。 – ndoogan 2013-03-14 18:52:22

+0

我也是,我的第一个虽然也是“为什么??” – 2013-03-14 18:55:17

+0

在我的情况下,我按照区域循环了线性模型,并且我的一些区域没有与其他区域相同数量的解释变量。在这种情况下,lm为模型系数返回NA,我想用零替换它,因为我的代码的其他下游元素取决于每个解释变量槽中的数值。 – MikeTP 2013-03-14 18:59:51

回答

2

你的代码是不可复制的,因为在你的代码的几个误区。下面是修改后的版本这也说明了自己的错误:

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 

所以,问题是,你正在使用fit$coef,虽然在lm输出组件的名字真coefficients。缩写版本用于获取值,但不用于设置,因为它使新组件名为coef,并且coef函数提取了值fit$coefficient

+0

谢谢你的编辑和anwser。 – MikeTP 2013-03-14 18:55:59