Closed ghost closed 2 years ago
Internally, plm
(and other functions) use a data structure called pdata.frame
which is sorted by individual (first sort criterion) and time dimension (second sort criterion). It is recommended to create a pdata.frame of your data beforehand (it is sorted) and then use that. The sorting will be the same then.
Something along these lines:
pFatalities <- pdata.frame(Fatalities, index = c("state", "year"))
mod <- plm(mrall ~ beertax, data = pFatalities, index = c("state", "year"), model = "within")
However, note that for arbitrary data the residuals might not fit to the original data as model estimation drops observations with NA
and NaN
values. To match the data correctly, you would need to merge them by individual and time index. Or use the data as used in estimation in mod$model
.
Many thanks!
I am using the State Traffic Fatality Data Set from Chapter 10 of Stock and Watson's Introduction to Econometrics (3rd edition), which can be found here. In my dataset, the order of the group variable
state
is not sorted:For example,
az
is in front ofar
, which is not following the alphabetical order. It is more obvious if we check the numeric values ofstate
plm()
gives the correct regression resultsHowever, if we calculate the fitted values using
and plot the regression lines using
we get
Clearly, the fitted values are not correct. The reason is
my_model_panel2$residuals
is sorted according to the values ofstate
. For example, the residuals forstate="az"
is put inmy_model_panel2$residuals[15:21]
, but it suppose to be inmy_model_panel2$residuals[8:14]
to match the order with the other variables.If we sorted it back according to the order of state using
and then calculate the new fitted values and plot them, we have![image](https://user-images.githubusercontent.com/98737389/151768336-37ac10ab-06c9-47af-bbec-0bad9f22b768.png)