## Introduction

The package hdpGLM makes it easy to estimate semi-parametric regression models, and summarize and visualize the results. The package is useful for many purposes:

1. Find clusters using semi-parametric Bayesian methods (Dirichlet Process)
2. Find a set of generalized linear models (GLM) that apply to different latent subpopulations
3. Estimate latent heterogeneity in the marginal effect of regression coefficients
4. Investigate if Simpson’s Paradox occurs due to latent or omitted features
5. Cluster the data points based on marginal effect heterogeneity
6. All the above, but with hierarchical data from many contexts (e.g., schools, hospitals, cities, states, countries, etc.)
7. Find the effect of context-level features (upper-level covariates) on the latent heterogeneity of within-context features (lower-level covariates)

## Background

The `hdpGLM` works similarly to linear regression models. It estimates coefficients of linear regressions, including generalized linear models, such as logit coefficients. But it simultaneously searches for latent clusters in the data and estimates the linear coefficients for those clusters. The result of the estimation is \(K\) vectors of linear coefficients, one vector for each cluster. If there are no clusters in the data, it returns the estimated coefficients similar to classical regression models.

The clustering procedure is based on a hierarchical semi-parametric Bayesian model proposed in Ferrari (2020). The model, called Hierarchical Dirichlet process Generalized Linear Models (hdpGLM), can be used to deal with latent heterogeneity in different situations, including those that emerge due to unobserved variables. It deals with the latent heterogeneity in two ways: (1) it finds latent clusters which can be better described by different regression models and (2) estimate the coefficient of those models. The hdpGLM can also be used with hierarchical data to estimate latent heterogeneity in multiple contexts and check if the clusters are context-dependent (see an example in section Estimating Context-dependent latent heterogeneity).

The linear model is estimated by sampling from the posterior distribution using a Gibbs sampler. Non-linear models (e.g., logit with binary outcomes) use Hamiltonian Monte Carlo within Gibbs. The algorithms are presented in Ferrari (2020).

Why should we estimate clusters of linear regressions instead of fitting a single regression model?

First, it improves the predictive performance of the regression model and keeps the interpretability of the regression coefficients. `hdpGLM` is much more flexible than traditional regression and produces monotonically lower root mean square error (see Ferrari (2020) for details).

Second, latent heterogeneity emerges when there are omitted variables in the estimation of regression models. The `hdpGLM` can be used to estimate marginal effects even when interactions were omitted. It recovers the linear coefficients of each latent group.

## Usage

### Estimation

The function `hdpGLM` estimates a semi-parametric Bayesian regression model. The syntax is similar to other R functions such as `lm()`, `glm()`, and `lmer()`.

Here is a toy example. Suppose we are studying how income inequality affects support policies that help alleviate poverty in a given country A. Yet, suppose further that (1) the effect of inequality varies between groups of people; for some people, inequality increases support for welfare policies, but for others, it decreases welfare policy support; (2) we don’t know which individual belongs to which group. The data set `welfare` contains simulated data for this example.

    ## loading and looking at the data
    welfare = read.csv2('welfare.csv')
    head(welfare)
    #>       support inequality     income   ideology
    #> 1 -18.5649610  0.3392724  0.1425111  1.9225985
    #> 2  -9.3905812 -0.9906646 -0.5117102  0.2483346
    #> 3   0.9276234 -2.2318510 -0.3856288 -1.3619216
    #> 4 -12.3594498 -3.0079501 -0.9440585 -0.2088675
    #> 5  -2.4834411  0.1000455  0.8322192  0.1321378
    #> 6 -11.4187853 -0.9543883 -0.8810503  0.2916444

Now, suppose that inequality increases support for welfare only among women, but it decreases support among men. We didn’t collect data on gender (male versus female). We could estimate the `hdpGLM` and recover the coefficients even if gender wasn’t observed. The package provides a function called `hdpGLM`, which estimates a semi-parametric Bayesian generalized linear model using a Dirichlet mixture. Let’s estimate the model. The example uses few iterations in the MCMC, but in real applications, one should use a much larger number.

    library(hdpGLM)
    #>
    #> ## ===============================================================
    #> ## Hierarchial Dirichlet Process Generalized Linear Model (hdpGLM)
    #> ## ===============================================================
    #>
    #> Author: Diogo Ferrari
    #> Usage : http://www.diogoferrari.com/hdpGLM/index.html
    #>
    #> Attaching package: 'hdpGLM'
    #> The following object is masked _by_ '.GlobalEnv':
    #>
    #>     welfare

    ## estimating the model
    mcmc = list(burn.in=10, ## MCMC burn-in period
                n.iter =500) ## number of MCMC iterations to keep
    mod = hdpGLM(support ~ inequality + income + ideology, data=welfare,
                 mcmc=mcmc)

    ## printing the outcome
    summary(mod)
    #>
    #> --------------------------------
    #> dpGLM model object
    #>
    #> Maximum number of clusters activated during the estimation: 16
    #> Numer of MCMC iterations: 500
    #> burn-in: 10
    #> --------------------------------
    #>
    #> Summary statistics of clusters with data points
    #>
    #> --------------------------------
    #> Coefficients for cluster 1 (cluster label 1)
    #>
    #>               Post.Mean Post.Median  HPD.lower HPD.upper
    #> 1 (Intercept) -3.870745   -3.871273 -3.9372547 -3.783851
    #> 2  inequality  1.998933    1.999023  1.9383191  2.065119
    #> 3      income  3.852747    3.852675  3.7825013  3.919162
    #> 4    ideology -8.304096   -8.304810 -8.3779430 -8.231231
    #> 5       sigma  1.000934    1.000591  0.9222278  1.084491
    #>
    #> --------------------------------
    #> Coefficients for cluster 2 (cluster label 9)
    #>
    #>                Post.Mean Post.Median  HPD.lower HPD.upper
    #> 1 (Intercept) -3.8184074  -3.8192347 -3.8848067 -3.739144
    #> 2  inequality -1.5249039  -1.5251752 -1.5880149 -1.452453
    #> 3      income  3.8824352   3.8825773  3.8064853  3.954712
    #> 4    ideology -8.2571529  -8.2572848 -8.3330580 -8.183055
    #> 5       sigma  0.9704992   0.9700404  0.8568248  1.077768
    #>
    #> --------------------------------

The summary function prints the result in a tidy format. The column `k` in the summary shows the label of the estimated clusters. The column `Mean` is the average of the posterior distribution for each linear coefficient in each cluster.

The function `classify` can be used to classify the data points into clusters based on the estimation.

    welfare_clustered = classify(welfare, mod)
    head(welfare_clustered)
    #>   Cluster     support inequality     income   ideology
    #> 1       1 -18.5649610  0.3392724  0.1425111  1.9225985
    #> 2       1  -9.3905812 -0.9906646 -0.5117102  0.2483346
    #> 3       1   0.9276234 -2.2318510 -0.3856288 -1.3619216
    #> 4       1 -12.3594498 -3.0079501 -0.9440585 -0.2088675
    #> 5       9  -2.4834411  0.1000455  0.8322192  0.1321378
    #> 6       1 -11.4187853 -0.9543883 -0.8810503  0.2916444
    tail(welfare_clustered)
    #>      Cluster     support  inequality     income   ideology
    #> 1995       9  -1.5230053 1.055855140 -0.7295937 -0.7067871
    #> 1996       9   0.4814892 0.582588091  2.0051082  0.3090389
    #> 1997       9 -14.1929956 0.391164197 -0.9607449  0.7765482
    #> 1998       1  -8.2396789 0.074437376  1.2020300  1.0874928
    #> 1999       9 -23.1583753 0.434223018 -0.6176438  2.0387294
    #> 2000       1  -7.2075582 0.008355317 -0.4538951  0.2268072

There are a series of built-in functions, with various options, to plot the results. In the example below, you see two of those options. The `separate` parameter plot the posterior samples for each cluster separately, and the option `ncols` controls how many columns to use for the panels in the figure (to see more, run `help(plot.hdpGLM)` and `help(plot.dpGLM)`).

    plot(mod, separate=T, ncols=4)
    #>
    #>
    #> Generating plot...

### Estimating Context-dependent Latent Heterogeneity

To continue the previous toy example, suppose that we are analyzing data from many countries, and we suspect that the latent heterogeneity is different in each country. The effect of inequality on support for welfare may be gender-specific only in some countries (contexts). Or maybe the way it is gender-specific varies from country to country. Suppose we didn’t have data on gender, but we collect information on countries’ gender gap in welfare provision. Let’s look at this new data set.

    ## loading and looking at the data
    welfare = read.csv2('welfare2.csv')
    head(welfare)
    #>       support inequality     income   ideology country gap
    #> 1 -18.5649610  0.3392724  0.1425111  1.9225985       0 0.1
    #> 2  -9.3905812 -0.9906646 -0.5117102  0.2483346       0 0.1
    #> 3   0.9276234 -2.2318510 -0.3856288 -1.3619216       0 0.1
    #> 4 -12.3594498 -3.0079501 -0.9440585 -0.2088675       0 0.1
    #> 5  -2.4834411  0.1000455  0.8322192  0.1321378       0 0.1
    #> 6 -11.4187853 -0.9543883 -0.8810503  0.2916444       0 0.1
    tail(welfare)
    #>         support inequality     income    ideology country        gap
    #> 3195  0.3190583 -0.7504798 -0.7839583  0.92300705       4 -0.8280808
    #> 3196 -1.3837239  0.6620435 -1.5566268  0.05634618       4 -0.8280808
    #> 3197 -1.3820016 -0.4298706 -1.0945688  0.71559078       4 -0.8280808
    #> 3198  0.6878775  0.5450604  2.6175887 -1.94844469       4 -0.8280808
    #> 3199 -7.9282930  1.7846004  1.6755823  1.29160208       4 -0.8280808
    #> 3200 -1.7472485  0.5030992 -0.5395479  0.20109879       4 -0.8280808

The variable `country` indicates the country (context) of the observation, and the variable `gap` the gender gap in welfare provision in the respective country. The estimation is similar to the previous example, but now there is a second `formula` for the context-level variables. Again, the example below uses few iterations in the MCMC, but in practical applications, one needs to increase that).

    ## estimating the model
    mcmc = list(burn.in=1, ## MCMC burn-in period
                n.iter =50) ## number of MCMC iterations to keep
    mod = hdpGLM(support ~ inequality + income + ideology,
                 support ~ gap,
             data=welfare, mcmc=mcmc)

    summary(mod)
    #>
    #> --------------------------------
    #> hdpGLM Object
    #>
    #> Maximum number of clusters activated during the estimation: 1
    #> Numer of MCMC iterations: 50
    #> Burn-in: 1
    #>
    #> Number of contexts : 5
    #>
    #> Number of clusters (summary across contexts):
    #>
    #>   Average  Std.Dev Median Min. Max.
    #> 1     3.8 1.095445      4    2    5
    #> --------------------------------
    #>
    #>
    #> Summary statistics of clusters with data points in each context
    #>
    #> --------------------------------
    #> Coefficients and clusters for context 1
    #>
    #>                Post.Mean Post.Median HPD.lower  HPD.upper Cluster
    #> 1  (Intercept) -3.761428   -3.771248 -3.864421 -3.5027048       1
    #> 2   inequality -1.484083   -1.534678 -1.616683 -0.7499711       1
    #> 3       income  3.879462    3.882396  3.774988  3.9886461       1
    #> 4     ideology -8.257659   -8.269118 -8.380857 -8.0369345       1
    #> 5  (Intercept) -3.689410   -3.594898 -4.073907 -3.4777484       3
    #> 6   inequality  2.132635    2.152062  1.949586  2.2339621       3
    #> 7       income  3.875721    3.897136  3.694955  3.9638789       3
    #> 8     ideology -8.395083   -8.398066 -8.549199 -8.1152613       3
    #> 9  (Intercept) -4.135991   -4.119915 -4.519042 -3.9419748       4
    #> 10  inequality  1.837423    1.838560  1.611611  2.0460127       4
    #> 11      income  3.780745    3.786486  3.492423  4.0138943       4
    #> 12    ideology -8.212079   -8.284959 -8.498787 -7.5438859       4
    #> 13 (Intercept) -3.585939   -3.580628 -3.999386 -3.3275176       6
    #> 14  inequality  2.297557    2.273355  1.958788  2.8820032       6
    #> 15      income  4.316107    4.352829  3.712140  4.7519718       6
    #> 16    ideology -7.103224   -7.172574 -7.502413 -6.5254658       6
    #>
    #> --------------------------------
    #> Coefficients and clusters for context 3
    #>
    #>                  Post.Mean Post.Median  HPD.lower   HPD.upper Cluster
    #> 1  (Intercept) -1.01972494  -0.9502500 -3.5698961  0.17614910       2
    #> 2   inequality  0.33566451   0.6475783 -4.3723765  2.23232802       2
    #> 3       income -3.42609029  -3.6012512 -4.4005961 -1.84963000       2
    #> 4     ideology  0.02743495   1.0186052 -9.8687885  1.40664539       2
    #> 5  (Intercept)  0.27407288   0.6057320 -2.9319293  2.61216520       5
    #> 6   inequality  0.81914713   1.0496694 -3.2244425  4.55745982       5
    #> 7       income -1.95008265  -1.9142603 -7.8228012  1.12474710       5
    #> 8     ideology  0.79326369   0.8439503 -0.9768162  4.43579468       5
    #> 9  (Intercept) -0.21247282  -0.2154776 -0.4095234  0.06000963       6
    #> 10  inequality -0.59965740  -0.5757999 -0.7782928 -0.29451913       6
    #> 11      income -3.96004968  -4.0120927 -4.3278624 -3.63306485       6
    #> 12    ideology  0.74858027   0.6543076  0.4656465  1.39574302       6
    #> 13 (Intercept) -0.40891219  -0.1665331 -2.0543362  0.71347786       7
    #> 14  inequality  0.33519509   0.4952928 -0.9007382  0.78363120       7
    #> 15      income -3.13908189  -3.1348601 -4.1975067 -2.09945118       7
    #> 16    ideology  1.55395606   2.1930328 -2.5837170  2.64629105       7
    #>
    #> --------------------------------
    #> Coefficients and clusters for context 4
    #>
    #>                  Post.Mean Post.Median   HPD.lower   HPD.upper Cluster
    #> 1  (Intercept)  0.08458388   0.1036253 -0.10656874  0.26854517       2
    #> 2   inequality -1.24351101  -1.1234950 -1.73284993 -0.96408102       2
    #> 3       income -2.65917476  -2.6207384 -3.01106324 -2.47416175       2
    #> 4     ideology  0.17112921   0.1936271 -0.09124850  0.38057911       2
    #> 5  (Intercept) -0.11995853  -0.1332263 -0.45516307  0.22772784       3
    #> 6   inequality -0.42929930  -0.3420012 -1.03889211 -0.10322987       3
    #> 7       income -3.28779886  -3.3342870 -5.04496876 -3.04179163       3
    #> 8     ideology -1.55452088  -1.6054922 -2.63135390 -1.21171503       3
    #> 9  (Intercept)  0.56821304   0.5654671 -0.06006991  6.87520087       5
    #> 10  inequality -0.21440090  -0.3584463 -1.57828907  2.01061143       5
    #> 11      income -2.83550116  -2.8284259 -5.04087800 -2.33390705       5
    #> 12    ideology -0.51575757  -0.3123377 -2.50613175  1.36176785       5
    #> 13 (Intercept)  0.15182891   0.1093422 -0.57155433  0.65422756       6
    #> 14  inequality -1.34700826  -1.4510370 -1.70968255  0.27885980       6
    #> 15      income -2.54424248  -2.4895309 -2.98312733 -1.87148575       6
    #> 16    ideology -0.94517802  -0.8977156 -1.36595531 -0.04142274       6
    #>
    #> --------------------------------
    #> Coefficients and clusters for context 5
    #>
    #>                  Post.Mean Post.Median   HPD.lower    HPD.upper Cluster
    #> 1  (Intercept) -0.41076706 -0.42330112 -0.62709533 -0.228722047       2
    #> 2   inequality -1.90652980 -1.98379960 -2.41419022 -0.778159910       2
    #> 3       income  0.35921257  0.30631446 -0.09367145  0.974484572       2
    #> 4     ideology -0.60789102 -0.68681736 -1.15577145  0.013986403       2
    #> 5  (Intercept) -0.78556490 -0.72162660 -2.42877100 -0.572660814       4
    #> 6   inequality  0.61748017  0.72212411 -3.70521945  1.460257673       4
    #> 7       income -0.01009737 -0.06005723 -1.78212427  1.960554064       4
    #> 8     ideology -0.96783199 -0.97602856 -1.28083761 -0.153856716       4
    #> 9  (Intercept) -0.18284453 -0.16682425 -0.76590308  0.162066888       7
    #> 10  inequality  0.20182834  0.42979510 -0.68526959  0.915967609       7
    #> 11      income -0.99309544 -1.06376202 -1.81417075  0.009949559       7
    #> 12    ideology -1.99955938 -1.99192948 -2.38325066 -1.563746292       7
    #> 13 (Intercept)  0.08793006  0.15532892 -0.50444659  0.608187508       8
    #> 14  inequality  1.37162265  1.36445799  0.89161439  1.638011301       8
    #> 15      income -0.06733220 -0.10184715 -1.23457889  1.068965427       8
    #> 16    ideology -2.27355841 -2.27660165 -2.65535749 -1.974109528       8
    #> 17 (Intercept)  0.14827057  0.18719294 -1.51269874  1.202668238      10
    #> 18  inequality -2.72308234 -2.82317889 -3.19663915  0.094871656      10
    #> 19      income  0.04018461 -0.13301824 -0.42411609  2.214531168      10
    #> 20    ideology -2.65614903 -2.41344511 -6.70097257 -2.177476268      10
    #>
    #> --------------------------------
    #> Coefficients and clusters for context 2
    #>
    #>                Post.Mean Post.Median  HPD.lower  HPD.upper Cluster
    #> 1 (Intercept) -0.3332670  -0.2375420 -1.2300398  0.1010372       5
    #> 2  inequality -0.9952596  -1.2094112 -1.3972550  0.8999371       5
    #> 3      income -0.8110271  -0.6635803 -1.8099203 -0.4055808       5
    #> 4    ideology -2.3403821  -2.3317696 -2.8667931 -2.0694808       5
    #> 5 (Intercept)  1.2439450   1.1895780  0.8763158  2.0797700       8
    #> 6  inequality  0.8837189   0.9020004  0.4189504  1.1298293       8
    #> 7      income  0.9167082   0.9062979  0.7038610  1.1823324       8
    #> 8    ideology -1.6807154  -1.6481445 -2.2645260 -1.2892940       8
    #>
    #> --------------------------------
    #> Context-level coefficients:
    #>                Description    Post.Mean HPD.lower HPD.upper
    #> 1     Intercept of beta[0] -0.711431821 -3.212432  2.236799
    #> 2     Intercept of beta[1] -0.214301686 -2.339976  3.165643
    #> 3     Intercept of beta[2] -0.105059321 -2.983060  2.039523
    #> 4     Intercept of beta[3] -1.188760896 -3.757565  1.277457
    #> 5 Effect of gap on beta[0] -0.001364097 -1.936352  2.560545
    #> 6 Effect of gap on beta[1]  0.607483773 -1.305599  2.242967
    #> 7 Effect of gap on beta[2] -0.931682076 -3.097443  1.350784
    #> 8 Effect of gap on beta[3]  0.515862538 -1.191230  2.198659
    #>
    #> --------------------------------

The `summary` contains more information now. As before, the column `k` indicates the estimated clusters. The column `j` indicates the country (context) of the estimated value for the respective cluster’s coefficient. The second summary (`$tau`) shows the marginal effect of the context-level feature (`gap`). Details of the interpretation can be found in Ferrari (2020).

There are a series of built-in functions to visualize the output. The function `plot_tau()` displays the estimation of the effect of the context-level variables.

    plot_tau(mod)

The function `plot_pexp_beta()` displays the association between the context-level features and the latent heterogeneity in the effect of the linear coefficients in each context. The paramter ‘smooth.line’ plots a line representing the linear association between the context-level feature (`gap`) and the posterior averages of the marginal effects in each cluster. The parameter `ncol.beta` controls the number of columns in the figure for the panels. For more options, see `help(plot_pexp_beta)`

    plot_pexp_beta(mod, smooth.line=TRUE, ncol.beta=2)
    #>
    #>
    #> Generating plots ...
    #> Warning: `guides(<scale> = FALSE)` is deprecated. Please use `guides(<scale> =
    #> "none")` instead.
    #> `geom_smooth()` using formula 'y ~ x'
    #> `geom_smooth()` using formula 'y ~ x'

## Reference

Ferrari, Diogo. 2020. “Modeling Context-Dependent Latent Effect Heterogeneity.” Political Analysis 28 (1): 20–46.