plm: using fixef() to manually calculate fitted values for a fixed effects twoways model

后端 未结 4 903
北恋
北恋 2021-02-19 21:44

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

4条回答
  •  心在旅途
    2021-02-19 22:21

    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).

提交回复
热议问题