Fit Linear Model Using "fitlm(" With 3-Way and 4-Way Interactions

13 visualizzazioni (ultimi 30 giorni)
I want to create a linear regression model with 2, 3, and 4-way interactions. However, currently, my code will only return a 2-way interaction. How do I get the 3-way and 4-way interactions?
Here's my current code and the results:
y =[45; 71; 48; 65; 68; 60; 80; 65; 43; 100; 45; 104; 75; 86; 70; 96];
g1 = {'−'; '+'; '−'; '+'; '−'; '+'; '−'; '+'; '−'; '+'; '−'; '+'; '−'; '+'; '−'; '+'};
g2 = {'−'; '−'; '+'; '+'; '−'; '−'; '+'; '+'; '−'; '−'; '+'; '+'; '−'; '−'; '+'; '+'};
g3 = {'−'; '−'; '−'; '−'; '+'; '+'; '+'; '+'; '−'; '−'; '−'; '−'; '+'; '+'; '+'; '+'};
g4 = {'−'; '−'; '−'; '−'; '−'; '−'; '−'; '−'; '+'; '+'; '+'; '+'; '+'; '+'; '+'; '+'};
tbl = table(y,g1,g2,g3,g4);
lm = fitlm(tbl, 'interactions')
lm =
Linear regression model:
y ~ 1 + g1*g2 + g1*g3 + g1*g4 + g2*g3 + g2*g4 + g3*g4
Estimated Coefficients:
Estimate SE tStat pValue
________ ______ _________ __________
(Intercept) 45.188 4.1922 10.779 0.00011917
g1_+ 23 5.0559 4.5491 0.0061175
g2_+ 1 5.0559 0.19779 0.851
g3_+ 26.75 5.0559 5.2908 0.0032162
g4_+ -0.5 5.0559 -0.098894 0.92507
g1_+:g2_+ 0.25 5.0559 0.049447 0.96248
g1_+:g3_+ -36.25 5.0559 -7.1698 0.00082085
g1_+:g4_+ 33.25 5.0559 6.5764 0.00122
g2_+:g3_+ 4.75 5.0559 0.93949 0.39061
g2_+:g4_+ -0.75 5.0559 -0.14834 0.88787
g3_+:g4_+ -2.25 5.0559 -0.44502 0.67491
Number of observations: 16, Error degrees of freedom: 5
Root Mean Squared Error: 5.06
R-squared: 0.978, Adjusted R-Squared 0.933
F-statistic vs. constant model: 21.9, p-value = 0.00163

Risposte (1)

Samayochita
Samayochita il 25 Apr 2025
Hi Sarah,
The issue is in the model specification string you are passing to “fitlm”. The model specification is specified as “interactions” which only includes up to two-way interactions.
To include 3-way and 4-way interactions, you need to manually specify the formula in the form “y ~ terms”, where the terms are in Wilkinson Notation.
Here is how you can include all interactions up to 4-way:
lm = fitlm(tbl, 'y ~ g1*g2*g3*g4');
For more information, please refer to the following documentation links:
I hope this answer was helpful!

Prodotti


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by