如何在 R 中固定自變數的係數?
在進行分析時,我們可能會了解自變數的變化,或者我們可能希望瞭解如果我們固定某個變數,其他自變數的行為如何。因此,我們可以在建立模型時固定自變數的係數,這可以透過使用 offset 函式和我們想要固定係數值的變數的係數來實現。
示例
考慮以下資料框
> set.seed(854) > x1<-rnorm(20,5,0.34) > x2<-rnorm(20,5,1.96) > y1<-rnorm(20,10,1.20) > df1<-data.frame(x1,x2,y1) > df1
輸出
x1 x2 y1 1 5.055384 4.179533 10.432503 2 4.504170 4.239420 9.965098 3 4.790987 6.854590 12.394971 4 5.225883 5.302747 9.959724 5 5.331538 7.986233 10.652037 6 5.437044 4.479045 10.631804 7 4.880098 6.737453 11.647296 8 5.027229 3.380460 10.336230 9 5.114676 5.252512 10.005986 10 4.971399 3.423199 10.892680 11 5.360185 8.004727 10.988475 12 4.938459 6.348125 7.740576 13 5.490242 5.362272 8.400993 14 5.104938 4.410061 8.559530 15 5.680805 4.225577 9.805985 16 5.321608 5.213297 8.401131 17 5.095157 8.048281 10.927522 18 5.153315 2.422241 9.090280 19 5.534677 2.886866 8.402550 20 4.625666 4.487508 9.957264
建立預測 y1 的模型,並固定 x2 的係數
> Model1<-lm(y1~x1+offset(5*x2),data=df1) > summary(Model1)
呼叫
lm(formula = y1 ~ x1 + offset(5 * x2), data = df1)
殘差
Min 1Q Median 3Q Max -13.4830 -6.2440 0.9653 4.9613 12.8422
係數
Estimate Std. Error t value Pr(>|t|) (Intercept) -13.0038 32.2757 -0.403 0.692 x1 -0.5549 6.2786 -0.088 0.931
殘差標準誤差:18 自由度的 8.269
多重 R 平方:0.5247,調整後的 R 平方:0.4983
F 統計量:1 和 18 DF 的 19.87,p 值:0.0003043
示例
讓我們看看另一個例子
> a1<-rpois(20,5) > a2<-rpois(20,8) > Response<-sample(1:10,20,replace=TRUE) > df2<-data.frame(a1,a2,Response) > df2
輸出
a1 a2 Response 1 3 7 8 2 7 11 8 3 10 8 3 4 6 5 6 5 4 5 8 6 16 10 7 7 4 8 10 8 5 11 1 9 6 4 4 10 5 12 2 11 5 9 7 12 5 8 8 13 7 6 2 14 2 10 9 15 5 10 1 16 5 6 10 17 2 6 7 18 6 11 1 19 8 12 1 20 4 11 4
建立預測 Response 的模型,並固定 a1 的係數
> Model2<-lm(Response~offset(1.34*a1)+a2,data=df2) > summary(Model2)
呼叫
lm(formula = Response ~ offset(1.34 * a1) + a2, data = df2)
殘差
Min 1Q Median 3Q Max -10.890 -3.164 1.325 3.358 9.870
係數
Estimate Std. Error t value Pr(>|t|) (Intercept) 4.4180 4.4255 0.998 0.331 a2 -0.7968 0.4998 -1.594 0.128
殘差標準誤差:18 自由度的 5.543
多重 R 平方:0.3836,調整後的 R 平方:0.3494
F 統計量:1 和 18 DF 的 11.2,p 值:0.003587
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP