如何创建仅在R中具有交互项的线性模型?
要仅创建具有交互项的线性模型,我们可以在创建模型时使用交互变量。例如,如果我们有一个名为df的数据框,它具有两个自变量V1和V2以及一个因变量Y,则仅具有交互项的线性模型可以创建为lm(Y〜V1:V2,data = df)。
考虑以下数据帧-
示例
x1<-rnorm(20,5,1.2)输出结果x2<-rnorm(20,2,1.2)
y1<-rnorm(20,3,1.25)
df1<-data.frame(x1,x2,y1)
df1
x1 x2 y11 4.442636 2.63714281 0.9120181
2 5.912804 1.72409663 2.2746513
3 7.881736 3.48780844 3.2675991
4 6.145395 1.51225991 3.2177194
5 6.303181 4.34733534 3.3361897
6 5.689431 0.08564247 2.0863346
7 6.008397 1.30221198 2.7183725
8 6.580716 1.45239970 4.0301650
9 4.000381 3.71539569 3.9404225
10 5.535338 3.48976926 4.9557343
11 5.968661 2.18208048 3.9992293
12 4.783326 -0.90756376 4.2661775
13 3.843528 -0.50299042 0.6496255
14 6.034803 1.06019093 5.2339701
15 4.177977 1.70476660 2.5932408
16 5.746300 0.85021792 3.0145627
17 4.658000 1.49894326 5.2826538
18 3.797983 0.46900834 3.6511403
19 5.415130 -0.31811078 2.6574529
20 4.709443 2.72001915 1.8893078
通过x1和x2之间的相互作用为y1创建线性模型-
Model1<-lm(y1~x1:x2,data=df1)summary(Model1)
打电话-
lm(formula = y1 ~ x1:x2, data = df1)
残差-
Min 1Q Median 3Q Max-2.3517 -0.6387 -0.1708 0.7321 2.1390
系数-
Estimate Std. Error t value Pr(>|t|)(Intercept) 2.96669 0.42803 6.931 1.77e-06 ***
x1:x2 0.02535 0.03434 0.738 0.47
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 1.299 on 18 degrees of freedomMultiple R-squared: 0.02939, Adjusted R-squared: -0.02454
F-statistic: 0.545 on 1 and 18 DF, p-value: 0.4699
示例
v1<-rpois(20,2)输出结果v2<-rpois(20,2)
v3<-rpois(20,2)
Response<-rpois(20,5)
df2<-data.frame(v1,v2,v3,Response)
df2
v1 v2 v3 Response1 2 2 4 10
2 1 1 2 2
3 3 4 3 4
4 2 1 2 5
5 0 0 2 4
6 0 2 1 5
7 1 3 0 5
8 0 0 1 6
9 1 3 1 6
10 3 0 2 6
11 2 1 0 3
12 1 3 1 2
13 2 1 3 5
14 0 1 0 8
15 0 3 1 4
16 1 0 3 2
17 3 1 3 2
18 0 4 1 9
19 1 2 3 9
20 3 2 0 9
通过v1,v2和v3之间的交互为响应创建线性模型-
Model2<-lm(Response~v1:v2+v2:v3+v1:v3+v1:v2:v3,data=df2)summary(Model2)
打电话-
lm(formula = Response ~ v1:v2 + v2:v3 + v1:v3 + v1:v2:v3, data = df2)
残差-
Min 1Q Median 3Q Max-4.3677 -1.7339 -0.0289 1.7127 4.0160
系数-
Estimate Std. Error t value Pr(>|t|)(Intercept) 3.98404 1.21641 3.275 0.00511 **
v1:v2 0.31934 0.44221 0.722 0.48131
v2:v3 0.83716 0.46012 1.819 0.08886 .
v1:v3 0.02783 0.30125 0.092 0.92762
v1:v2:v3 -0.37123 0.28280 -1.313 0.20901
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.609 on 15 degrees of freedomMultiple R-squared: 0.1907, Adjusted R-squared: -0.02517
F-statistic: 0.8834 on 4 and 15 DF, p-value: 0.4973
以上是 如何创建仅在R中具有交互项的线性模型? 的全部内容, 来源链接: utcz.com/z/320037.html