替换[r]中的lm系数 [英] Replace lm coefficients in [r]

查看:63
本文介绍了替换[r]中的lm系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

任何帮助将不胜感激

推荐答案

您的代码不可复制,因为您的代码中几乎没有错误.这是更正后的版本,还显示了您的错误:

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 

所以问题在于您使用的是fit$coef,尽管lm 输出中的组件名称实际上是coefficients.缩写版本用于获取值,但不适用于设置,因为它创建了名为 coef 的新组件,并且 coef 函数提取了 fit $ coefficient的值.

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.

这篇关于替换[r]中的lm系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆