【问题标题】:Replace lm coefficients in [r]替换 [r] 中的 lm 系数
【发布时间】:2013-03-15 03:00:54
【问题描述】:

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

任何帮助将不胜感激

【问题讨论】:

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

标签: r lm


【解决方案1】:

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

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-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2014-08-09
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2022-09-23
    相关资源
    最近更新 更多