lrberge / fixest

Fixed-effects estimations
https://lrberge.github.io/fixest/
362 stars 59 forks source link

Problem with fepois out-of-sample prediction when using offset #388

Closed mariofiorini closed 5 months ago

mariofiorini commented 1 year ago

Hi Laurent, first of all many thanks for creating such a great package. I am using fepois with an offset variable, and then trying to do some out-of-sample prediction, but I always get some error message. Small example, where I

library(fixest)
data(trade)

gravity_pois_1 = fepois(Euros ~ 1 | Origin, offset = log(trade[trade$Destination!='IT','dist_km']), trade[trade$Destination!='IT',])

predict(gravity_pois_1, newdata = trade,  type = 'response' )

Error in predict.fixest(gravity_pois_1, newdata = trade, type = "response") : 
  Predict can't be applied to this estimation because the offset (log(trade[trade$Destination != "IT", "dist_km"])) cannot be evaluated for the new data. Use a formula for the offset in the first estimation to avoid this.

Then I try to have offset in the main formula but I get a different error message when trying to predict

gravity_pois_2 = fepois(Euros ~ 1 + offset(log(dist_km)) | Origin , trade[trade$Destination!='IT',])

predict(gravity_pois_2, newdata = trade,  type = 'response' )

Error in matrix_linear[, var_keep, drop = FALSE] %*% coef[var_keep] : 
  requires numeric/complex matrix/vector arguments

Let me know if I am missing something. Cheers, Mario

mariofiorini commented 1 year ago

Tthe solution (thanks Laurent) is to add ~ to define a formula for the offset. I hope it can be useful to others:

gravity_pois_3 = fepois(Euros ~ 1 | Origin , trade[trade$Destination!='IT',], offset = ~log(dist_km))
predict(gravity_pois_3, newdata = trade,  type = 'response' )

so ~log(dist_km) works. I will close the issue.

lrberge commented 1 year ago

Hi Mario: the second call is still a bug so I'm reopening the issue until I fix it. Thanks for reporting!

lrberge commented 5 months ago

Maybe it was a version issue, the second call currently works. Thanks for reporting.