2

是否可以替换 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)

任何帮助将不胜感激

4

1 回答 1

3

您的代码不可重现,因为您的代码几乎没有错误。这是更正的版本,也显示了您的错误:

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

于 2013-03-14T18:51:48.767 回答