Please note: I am trying to get the code to work with both time & individual fixed effects, and an unbalanced dataset. The sample code below works
Edit: adapted to two-ways unbalanced model, needs plm version >= 2.4-0
Is this what you wanted? Extract the fixed effects by fixef
. Here is an example for the Grunfeld data on an unbalanced two-way model (works the same for the balanced two-way model):
gtw_u <- plm(inv ~ value + capital, data = Grunfeld[-200, ], effect = "twoways")
yhat <- as.numeric(gtw_u$model[ , 1] - gtw_u$residuals) # reference
pred_beta <- as.numeric(tcrossprod(coef(gtw_u), as.matrix(gtw_u$model[ , -1])))
pred_effs <- as.numeric(fixef(gtw_u, "twoways")) # sum of ind and time effects
all.equal(pred_effs + pred_beta, yhat) # TRUE -> matches fitted values (yhat)
If you want to split the sum of individual and time effects (given by effect = "twoways"
) in its components, you will need to choose a reference and two come naturally to mind which are both given below:
# Splits of summed up individual and time effects:
# use one "level" and one "dfirst"
ii <- index(gtw_u)[[1L]]; it <- index(gtw_u)[[2L]]
eff_id_dfirst <- c(0, as.numeric(fixef(gtw_u, "individual", "dfirst")))[ii]
eff_ti_dfirst <- c(0, as.numeric(fixef(gtw_u, "time", "dfirst")))[it]
eff_id_level <- as.numeric(fixef(gtw_u, "individual"))[ii]
eff_ti_level <- as.numeric(fixef(gtw_u, "time"))[it]
all.equal(pred_effs, eff_id_level + eff_ti_dfirst) # TRUE
all.equal(pred_effs, eff_id_dfirst + eff_ti_level) # TRUE
(This is based on the man page of fixef, ?fixef
. There it is also shown how the (balanced and unbalanced) one-way model is to be handled).