2013-03-14 37 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