替换[r]中的lm系数

替换[r]中的lm系数,r,lm,R,Lm,是否可以替换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 f

是否可以替换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)
#示例数据
种子集(215710)

x1您的代码不可复制,因为代码中几乎没有错误。以下是更正的版本,其中也显示了您的错误:

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 
set.seed(215710)#忘记设置。

x1我很好奇为什么会有人想这样做。我也是,我的第一个想法也是“为什么?”。在我的例子中,我按区域循环线性模型,我的一些区域没有与其他区域相同数量的解释变量。在这种情况下,lm为模型系数返回NA,我想将其替换为零,因为我代码的其他下游元素依赖于每个解释变量槽中的数值。@MikeTP现在我明白了,我也为您的相关问题编写了一个解决方案。是的,我感谢这两个回答