I asked the same question here but have not received an answer for a week now, probably because its more of a coding than statistics question
I want to perform a mediation analysis with a fixed effects model as base model in python. I know, that you can perform mediation analysis using statsmodels' Mediation module. But fixed effects models (as far as I know) are only possible with linearmodels. As I haven't performed a mediation analysis so far, I'm not to sure how to combine those two modules.
I've tried the following (from step 3 onward is relevant for my question):
import pandas as pd
from linearmodels import PanelOLS
import statsmodels.api as sm2
from statsmodels.stats.mediation import Mediation
##1. direct effect: X --> Y
DV_LF = df.Y
IV_X = sm2.add_constant(df[['X', 'Control']])
fe_mod_X = PanelOLS(DV_LF, IV_X, entity_effects=True )
fe_res_X = fe_mod_X.fit(cov_type='clustered', cluster_entity=True)
print(fe_res_X)
##2. X --> M
DV_A = df.M
IV_A = sm2.add_constant(df[['X', 'Control']])
fe_mod_A = PanelOLS(DV_A, IV_A, entity_effects=True )
fe_res_A = fe_mod_A.fit(cov_type='clustered', cluster_entity=True)
print(fe_res_A)
##3. M --> Y
IV_M = sm2.add_constant(df[['M', 'Control']])
fe_mod_M = PanelOLS(DV_LF, IV_M, entity_effects=True )
fe_res_M = fe_mod_M.fit(cov_type='clustered', cluster_entity=True)
print(fe_res_M)
##4. X, M --> Y
IV_T = sm2.add_constant(df[['X', 'M', 'Control']])
fe_mod_T = PanelOLS(DV_LF, IV_T, entity_effects=True )
fe_res_T = fe_mod_T.fit(cov_type='clustered', cluster_entity=True)
print(fe_res_T)
med = Mediation(fe_res_T, fe_res_A, 'X', 'M').fit()
med.summary()
but I'm running into an error:
AttributeError: 'PanelEffectsResults' object has no attribute 'exog'
Does my approach make sense? If so how do I have to change the code to make PanelOLS and Mediation work together?
EDIT:
Would it be valid to calculate the indirect effect by multiplying the coefficient of X on M (step 2) with the coefficient of M on Y from step 4 and the direct effect by subtracting the indirect effect off the coefficient of X on Y (step 1)? I'm a little bit confused by that research poster, saying, that normal mediation analysis are not valid for within subject analysis such as Fixed Effects. If my approach is valid, how would I calculate the significance of the difference between the direct and the total effect? I read that bootstrapping would be a good choice, but I am unsure how to apply it in my case.