Package {PAGFL}


Title: Joint Estimation of Latent Groups and Group-Specific Coefficients in (Time-Varying) Panel Data Models
Version: 1.2.1
Maintainer: Paul Haimerl <paul.haimerl@econ.au.dk>
Description: Latent group structures are common in panel data. Ignoring differences between groups can introduce bias, while estimating separate coefficients for every cross-sectional unit can be imprecise. The package implements the pairwise adaptive group fused Lasso (PAGFL) of Mehrabani (2023) <doi:10.1016/j.jeconom.2022.12.002>, which estimates latent groups and their coefficients jointly. It also implements FUSE-TIME, the extension to time-varying coefficients by Haimerl et al. (2026) <doi:10.1093/ectj/utag034>.
Depends: R (≥ 3.5.0)
License: AGPL (≥ 3)
Encoding: UTF-8
LinkingTo: Rcpp, RcppArmadillo, RcppParallel, RcppThread
Imports: Rcpp, lifecycle, ggplot2, RcppParallel, RhpcBLASctl, splines
BugReports: https://github.com/Paul-Haimerl/PAGFL/issues
URL: https://github.com/Paul-Haimerl/PAGFL
Suggests: testthat (≥ 3.0.0)
Config/testthat/edition: 3
Config/roxygen2/version: 8.1.1
NeedsCompilation: yes
Packaged: 2026-12-01 18:59:04 UTC; au772358
Author: Paul Haimerl ORCID iD [aut, cre], Stephan Smeekes ORCID iD [ctb], Ines Wilms ORCID iD [ctb], Ali Mehrabani ORCID iD [ctb]
Repository: CRAN
Date/Publication: 2026-12-02 09:20:12 UTC

Fused Unobserved group Spline Estimation of TIME-varying coefficients

Description

Estimate a time-varying panel model with latent groups using FUSE-TIME (Fused Unobserved group Spline Estimation of TIME-varying coefficients) of Haimerl et al. (2026). FUSE-TIME jointly identifies the groups and estimates their time-varying coefficients. The time-varying coefficients are approximated as polynomial B-splines. The function supports both static and dynamic panel data models.

Usage

fuse_time(
  formula,
  data,
  index = NULL,
  n_periods = NULL,
  lambda,
  d = 3,
  M = floor(length(y)^(1/7) - log(p)),
  lambda_smooth = 0,
  scale_smooth = FALSE,
  min_group_frac = 0.05,
  const_coef = NULL,
  global_coef = NULL,
  ind_coef = NULL,
  kappa = 2,
  max_iter = 50000,
  tol_convergence = 1e-10,
  tol_group = 0.001,
  rho = 0.04 * log(N * n_periods)/sqrt(N * n_periods),
  varrho = 1,
  verbose = TRUE,
  parallel = TRUE,
  ...
)

tv_pagfl(
  formula,
  data,
  index = NULL,
  n_periods = NULL,
  lambda,
  d = 3,
  M,
  min_group_frac = 0.05,
  const_coef = NULL,
  kappa = 2,
  max_iter = 50000,
  tol_convergence = 1e-10,
  tol_group = 0.001,
  rho,
  varrho = 1,
  verbose = TRUE,
  parallel = TRUE,
  ...
)

## S3 method for class 'fusetime'
summary(object, ...)

## S3 method for class 'fusetime'
formula(x, ...)

## S3 method for class 'fusetime'
df.residual(object, ...)

## S3 method for class 'fusetime'
print(x, ...)

## S3 method for class 'fusetime'
coef(object, ...)

## S3 method for class 'fusetime'
residuals(object, ...)

## S3 method for class 'fusetime'
fitted(object, ...)

Arguments

formula

A formula specifying the model to estimate.

data

A data.frame or matrix containing panel data. Without index, the panel must be balanced and ordered in long format \bold{Y}=(Y_1^\prime, \dots, Y_N^\prime)^\prime, Y_i = (Y_{i1}, \dots, Y_{iT})^\prime with Y_{it} = (y_{it}, \bold{x}_{it}^\prime)^\prime. Otherwise, data must contain variables identifying the cross-sectional unit i and time period t of each observation.

index

A character vector naming the cross-sectional unit i and time period t variables, in that order. Data are sorted by these variables; a character time index may cause errors. For a balanced panel already ordered in long format, index may be omitted if n_periods is supplied.

n_periods

The number of observed time periods T. May be omitted when index is supplied. Default is NULL.

lambda

The tuning parameter determining the strength of the penalty term. Either a single \lambda or a vector of candidate values can be passed. If a vector is supplied, a BIC-type IC automatically selects the best-fitting \lambda value.

d

The polynomial degree of the B-splines. Default is 3.

M

The number of interior knots of the B-splines. The default is M = \max\{\lfloor n^{1/7} - \log(p_{\mathrm{TV}})\rfloor, 1\}, where n is the number of retained observations and p_{\mathrm{TV}} counts all time-varying regressors, including global and individual ones. In the balanced baseline model, this is the heuristic of Haimerl et al. (2026, sec. 4.1). Package M is the paper's M^*; the spline basis dimension is M + d + 1.

lambda_smooth

A numeric value \geq 0 controlling the O'Sullivan curvature penalty on time-varying coefficient functions (see Details). lambda_smooth = 0 disables curvature penalisation; the fusion penalty remains. Positive values require d \geq 2. Time-constant coefficients in const_coef are not penalised. Default is 0.

scale_smooth

Logical. If TRUE, the curvature penalty of each time-varying regressor is weighted by the regressor's mean square, so that it does not depend on the regressor's units (see Details). No effect if lambda_smooth = 0. Default is FALSE.

min_group_frac

The minimum group size as a fraction of N. If a group falls below this threshold, its members are assigned to the remaining groups according to the MSE. Default is 0.05.

const_coef

A character vector containing the variable names of explanatory variables that enter with time-constant coefficients.

global_coef

A character vector containing the variable names of explanatory variables whose coefficient is common to all cross-sectional units and therefore excluded from the fusion penalty (see Details). A variable appearing in both const_coef and global_coef obtains a global and time-constant coefficient. Default is NULL.

ind_coef

A character vector containing the variable names of explanatory variables whose coefficient is specific to each cross-sectional unit and therefore excluded from the fusion penalty (see Details). A variable appearing in both const_coef and ind_coef obtains an individual and time-constant coefficient. Default is NULL.

kappa

A positive exponent used to obtain the adaptive penalty weights. Default is 2.

max_iter

The maximum number of iterations for the ADMM estimation algorithm. Default is 5*10^4.

tol_convergence

The tolerance limit for the stopping criterion of the iterative ADMM estimation algorithm. Default is 1*10^{-10}.

tol_group

The tolerance for differences between individual spline coefficient vectors. Pairs whose Euclidean distance is below this threshold are linked; groups are formed by transitive closure (see Details). Default is 1*10^{-3}.

rho

The tuning parameter balancing the fit and complexity terms in the IC that determines \lambda. The default \rho = 0.04 \frac{\log(NT)}{\sqrt{NT}} follows Haimerl et al. (2026, sec. 3.3, eq. 3.1). Here T is the number of distinct retained time periods, including for an unbalanced panel. We recommend the default.

varrho

The positive Lagrangian ADMM penalty parameter. It controls numerical convergence without changing the objective. Default is 1.

verbose

Logical. If TRUE, messages are shown. Default is TRUE.

parallel

Logical. If TRUE, computation is parallelised across multiple cores. When lambda is a grid with more than two values, the search over \lambda is dispatched in parallel, with each penalty value fitted independently from a cold start; otherwise certain inner per-iteration operations of the ADMM algorithm are parallelised via RcppParallel. Results are numerically identical to the sequential path. A warning is issued when a memory estimate exceeds 4 GiB, including when parallel = FALSE. The estimate covers shared dense setup matrices and five pair-length vectors per fit; for a parallel grid search, it assumes all candidate fits run concurrently. Actual concurrency may be lower, and SVD workspaces and other allocations are excluded. The number of workers defaults to all logical cores and can be set via RcppParallel::setThreadOptions() or the RCPP_PARALLEL_NUM_THREADS environment variable. Default is TRUE.

...

Additional arguments.

object

An object of class fusetime.

x

An object of class fusetime.

Details

Consider the grouped time-varying panel data model of Haimerl et al. (2026, sec. 2.1, eqs. 2.1–2.3)

y_{it} = \gamma_i^0 + \bold{\beta}^{0\prime}_{i} (t/T) \bold{x}_{it} + \epsilon_{it}, \quad i = 1, \dots, N, \; t = 1, \dots, T,

where y_{it} is the scalar dependent variable, \gamma_i^0 is an individual fixed effect, \bold{x}_{it} is a p \times 1 vector of explanatory variables, and \epsilon_{it} denotes a zero-mean error. The p-dimensional coefficient vector \bold{\beta}_{i}^0 (t/T) contains smooth functions of time and follows the latent group pattern

\bold{\beta}_i^0 \left(\frac{t}{T} \right) = \sum_{k = 1}^K \bold{\alpha}_k^0 \left( \frac{t}{T} \right) \bold{1} \{i \in G_k^0 \},

with \cup_{k = 1}^K G_k^0 = \{1, \dots, N\}, G_k^0 \cap G_j^0 = \emptyset, and \sup_{v \in [0,1]} \| \bold{\alpha}_k^0(v) - \bold{\alpha}_j^0(v) \| \neq 0 for any k \neq j, k,j = 1, \dots, K. Estimation requires suitable regressor–error orthogonality and regularity conditions; see the paper's Section 3 and Appendix A. Dynamic specifications can retain Nickell bias; this function does not apply a time-varying bias correction (sec. 3.2).

The time-varying coefficient functions are estimated as polynomial B-splines. To this end, let \bold{b}(v) denote a M + d +1 vector of polynomial basis functions with the polynomial degree d and M interior knots. The displays use the paper's t/T notation. The package places boundary knots at the first and last retained time indices, corresponding to v = (t - 1)/(T - 1); finite-sample knot locations therefore differ from the paper's convention. Then, \bold{\beta}_i^0 (t/T) is approximated by forming linear combinations of these basis functions \bold{\beta}_i^0 (t/T) \approx \bold{\Pi}_i^{0 \prime} \bold{b} (t/T), where \bold{\Pi}_i^{0} is a (M + d + 1) \times p matrix of spline control points.

To estimate \bold{\Pi}_i^{0}, we expand the explanatory variables in the spline basis, resulting in the (M + d + 1)p \times 1 regressor vector \bold{z}_{it} = \bold{x}_{it} \otimes \bold{b}(t/T). Subsequently, the DGP can be reformulated as

y_{it} = \gamma_i^0 + \bold{\pi}_{i}^{0 \prime} \bold{z}_{it} + u_{it},

where \bold{\pi}_i^0 = \text{vec}(\bold{\Pi}_i^0) and u_{it} = \epsilon_{it} + \eta_{it}. Here \eta_{it} = [\bold{\beta}_i^0(t/T) - \bold{\Pi}_i^{0\prime}\bold{b}(t/T)]^\prime \bold{x}_{it} is the sieve approximation error in the response equation (Haimerl et al., 2026, sec. 2.2, eqs. 2.4–2.5).

Following Haimerl et al. (2026, sec. 2.2, eq. 2.6), FUSE-TIME jointly estimates the functional coefficients and group structure by minimising the balanced-panel criterion

F_{NT} (\bold{\pi}, \lambda) = \frac{1}{T} \sum^N_{i=1} \sum^{T}_{t=1}(\tilde{y}_{it} - \bold{\pi}_{i}^\prime \tilde{\bold{z}}_{it})^2 + \frac{\lambda}{N} \sum_{i = 1}^{N - 1} \sum_{j = i+1}^N \dot{\omega}_{ij} \| \bold{\pi}_i - \bold{\pi}_j \|_2

with respect to \bold{\pi} = (\bold{\pi}_1^\prime, \dots, \bold{\pi}_N^\prime)^\prime. The within transformation \tilde{a}_{it} = a_{it} - T^{-1} \sum^{T}_{t=1} a_{it}, a = \{y, \bold{z}\}, removes the individual fixed effects \gamma_i^0. The adaptive weights are \dot{\omega}_{ij} = \|\dot{\bold{\pi}}_i - \dot{\bold{\pi}}_j\|_2^{-\kappa}, using preliminary unit-wise least squares estimates when lambda_smooth = 0. The criterion is minimised using an alternating direction method of multipliers (ADMM) algorithm (Haimerl et al., 2026, Supplement S3, Algorithm 1).

Two individuals are linked if \| \hat{\bold{\pi}}_i - \hat{\bold{\pi}}_j \|_2 < \epsilon_{\text{tol}}, where \epsilon_{\text{tol}} is tol_group. Groups are the connected components of these links, so two members of a group need not be directly within the tolerance of each other (Haimerl et al., 2026, Supplement S3). Groups below min_group_frac are then merged into the remaining groups according to the MSE.

Given the estimated group structure, post-Lasso estimates \hat{\bold{\alpha}}^p_k (t/T) = \hat{\bold{\Xi}}^{p \prime}_k \bold{b}(t/T) are obtained using group-wise least squares (Haimerl et al., 2026, sec. 2.2; see grouped_tv_plm). These shared post-Lasso coefficient functions are returned in coefficients.

Setting lambda_smooth > 0 augments the criterion F_{NT} (\bold{\pi}, \lambda) with an O'Sullivan smoothness penalty (O'Sullivan 1986; Wand & Ormerod 2008) on each unit-specific coefficient function

F_{NT} (\bold{\pi}, \lambda) + \frac{\lambda_s}{T} \sum_{i = 1}^N \bold{\pi}_i^\prime \bold{P} \bold{\pi}_i,

where \lambda_s = lambda_smooth, \bold{P} = \bold{I}_p \otimes \bold{\Omega} (padded with zeros for time-constant coefficients, which remain unpenalised), and \bold{\Omega} = \int_0^1 \bold{b}^{\prime \prime}(v) \bold{b}^{\prime \prime}(v)^\prime \, dv is the exact curvature penalty matrix on the normalised time domain v \in [0,1] (see grouped_tv_plm for details on its construction and scale invariance). The quadratic penalty is used in three stages: (i) the preliminary unit-wise estimates that determine the adaptive weights \dot{\omega}_{ij}, (ii) the first primal update of the ADMM algorithm, whose system matrix becomes \tilde{\bold{Z}}^\prime \tilde{\bold{Z}} + \bold{I}_N \otimes \lambda_s \bold{P} + \varrho \bold{\Delta}^\prime \bold{\Delta} (the remaining ADMM steps are unaffected), and (iii) the post-Lasso estimates, which coincide with grouped_tv_plm applied to the estimated group structure with the same lambda_smooth value. The smoothness penalty is applied per unit, so a fused group of size |G_k| has a combined penalty of |G_k| \lambda_s within the ADMM, whereas the post-Lasso stage (and grouped_tv_plm) applies \lambda_s once per group; the reported coefficients are the post-Lasso estimates. The IC uses the penalised post-Lasso fit and counts the nominal number of spline coefficients per group in its complexity term. As lambda_smooth \to \infty, all coefficient functions approach linear functions of v. The curvature penalty requires d \geq 2. With scale_smooth = TRUE, each block of \bold{P} is weighted by the mean square of its regressor (see grouped_tv_plm). This makes the smoothness penalty invariant to the units of the regressors, but not the fusion penalty: the distances \| \bold{\pi}_i - \bold{\pi}_j \|_2 and tol_group remain in coefficient units, so the estimated groups can still depend on them.

Mixed global, group-specific and individual coefficients are discussed by Haimerl et al. (2026, Supplement S4.1), and mixed time-varying and time-constant coefficients in Supplement S4.2. The curvature penalties and effective degrees of freedom are package extensions whose asymptotic properties are not established in the paper.

Variables named in ind_coef obtain a coefficient that is specific to each cross-sectional unit, \bold{\psi}_i(t/T), instead of a group-specific one. The model becomes

y_{it} = \gamma_i^0 + \bold{\beta}^{0 \prime}_{i} (t/T) \bold{x}_{it} + \bold{\psi}^{0 \prime}_{i} (t/T) \bold{r}_{it} + \epsilon_{it},

where \bold{r}_{it} collects the individual regressors. The individual spline block uses the same curvature penalty as the grouped blocks, with lambda_smooth applied once per unit. The block is block-diagonal across units, so it is concentrated out first; global_coef may be supplied alongside it. At least one regressor must retain a grouped time-varying coefficient.

An individual time-varying regressor that is time-invariant within a unit identifies only the shape of \bold{\psi}_i(t/T), since unit i's fixed effect absorbs the level; such curves are centred. An individual time-varying intercept is allowed, but it cannot be combined with a grouped intercept, which it would absorb. There is one individual coefficient block per unit, estimated from that unit's observations; consistent estimation of individual curves requires a growing time dimension. The paper's baseline classification results are derived without this block.

Variables named in global_coef obtain a coefficient that is common to all cross-sectional units, \bold{\theta}(t/T), instead of a group-specific one. The model becomes

y_{it} = \gamma_i^0 + \bold{\beta}^{0 \prime}_{i} (t/T) \bold{x}_{it} + \bold{\theta}^{0 \prime} (t/T) \bold{w}_{it} + \epsilon_{it},

where \bold{w}_{it} collects the global regressors. At least one regressor must retain a grouped time-varying coefficient. A global spline block can receive the same curvature penalty as the grouped blocks. For a regressor that is constant within each unit, the fixed effects absorb the level of its global coefficient function; only its shape is identified. Unidentified constant-level combinations are removed before preliminary, ADMM and post-Lasso solves. For a regressor that varies within units, the level may be identified. Specifications in which the global coefficients are not identified at all, for instance a global intercept alongside a grouped intercept, result in an error.

To select \lambda, pass a logarithmically spaced grid with a lower limit near 0 and an upper limit that yields a fully homogeneous panel. A BIC-type information criterion selects a value from the grid (Haimerl et al., 2026, sec. 3.3, eq. 3.1).

Unbalanced panels are discussed by Haimerl et al. (2026, Supplement S4.3). The package demeans over each unit's observed periods and sums residual squares over observed rows, retaining the common 1/T scaling above. Pooling and spline interpolation require sufficient information in the observed design. Group-specific coefficient functions are reported only between each group's earliest and latest observations, with NA outside that span.

We refer to Haimerl et al. (2026) for more details on the baseline procedure.

Value

An object of class fusetime holding

model

a data.frame containing the dependent and explanatory variables as well as cross-sectional and time indices,

coefficients

Let p^{(1)} denote the number of grouped time-varying coefficients and p^{(2)} the number of grouped time-constant parameters. A list holding (i) a T \times p^{(1)} \times \hat{K} array of the post-Lasso group-specific functional coefficients and (ii) a \hat{K} \times p^{(2)} matrix of time-constant post-Lasso estimates. If global_coef is supplied, the list additionally holds (iii) a T \times p^{(3)} matrix of the global functional coefficients and (iv) a 1 \times p^{(4)} matrix of global time-constant estimates, for the p^{(3)} global time-varying and p^{(4)} global time-constant regressors. If ind_coef is supplied, tv_ind and const_ind contain a T \times q_{\mathrm{TV}} \times N array and an N \times q_{\mathrm{C}} matrix for the individual time-varying and time-constant regressors, respectively; absent blocks are omitted.

groups

a list containing (i) the total number of groups \hat{K} and (ii) a vector of estimated group memberships (\hat{g}_1, \dots, \hat{g}_N), where \hat{g}_i = k if i is assigned to group k,

residuals

a vector of residuals of the demeaned model,

fitted

a vector of fitted values on the original outcome scale, including the unit means removed by the within transformation,

args

a list of additional arguments,

IC

a list containing (i) the value of the IC, (ii) the employed tuning parameter \lambda, (iii) the MSE, and (iv) lambda_grid, a matrix reporting \lambda, the IC, the MSE, and the implied number of groups for each candidate \lambda, with the selected \lambda marked by an asterisk,

edf

a vector of effective degrees of freedom added by each grouped block after the individual smoother in the penalised post-Lasso fit. Only present if lambda_smooth > 0,

edf_global

the effective degrees of freedom added by the global block after the individual and grouped smoothers. Only present if global_coef is supplied and lambda_smooth > 0,

edf_ind

a named vector of individual smoother degrees of freedom, one per unit. Only present if ind_coef is supplied and lambda_smooth > 0. Its sum, plus the grouped and global contributions when present, is the joint model EDF excluding fixed effects. IC and residual degrees of freedom retain nominal coefficient counts,

convergence

a list containing (i) a logical variable indicating if convergence was achieved and (ii) the number of executed ADMM algorithm iterations,

call

the function call.

An object of class fusetime has print, summary, fitted, residuals, formula, df.residual, and coef S3 methods.

Author(s)

Paul Haimerl

References

Chiang, C.-T. (2005). Comparisons between simultaneous and componentwise splines for varying coefficient models. Annals of the Institute of Statistical Mathematics, 57(4), 637-653. doi:10.1007/BF02915430.

Haimerl, P., Smeekes, S., & Wilms, I. (2026). Estimation of latent group structures in time-varying panel data models. The Econometrics Journal. doi:10.1093/ectj/utag034.

O'Sullivan, F. (1986). A statistical perspective on ill-posed inverse problems. Statistical Science, 1(4), 502-518. doi:10.1214/ss/1177013525.

Wand, M. P., & Ormerod, J. T. (2008). On semiparametric regression with O'Sullivan penalized splines. Australian & New Zealand Journal of Statistics, 50(2), 179-198. doi:10.1111/j.1467-842X.2008.00507.x.

See Also

pagfl for the static (time-invariant) counterpart, grouped_tv_plm for estimation given an observed group structure, and sim_tv_DGP for simulating a time-varying panel data set with a latent group structure.

Examples

# Simulate a time-varying panel with a trend and a group pattern
set.seed(1)
sim <- sim_tv_DGP(N = 10, n_periods = 50, intercept = TRUE, p = 1)
df <- data.frame(y = c(sim$y))

# Run FUSE-TIME
estim <- fuse_time(y ~ ., data = df, n_periods = 50, lambda = 10, parallel = FALSE)
summary(estim)


Grouped Panel Data Model

Description

Estimate a panel data model subject to an observed group structure. Slope parameters are homogeneous within groups but heterogeneous across groups. This function supports both static and dynamic panel data models, with or without endogenous regressors.

Usage

grouped_plm(
  formula,
  data,
  groups,
  index = NULL,
  n_periods = NULL,
  method = "PLS",
  Z = NULL,
  global_coef = NULL,
  ind_coef = NULL,
  bias_correc = FALSE,
  rho = 0.07 * log(N * n_periods)/sqrt(N * n_periods),
  verbose = TRUE,
  parallel = TRUE,
  ...
)

## S3 method for class 'gplm'
print(x, ...)

## S3 method for class 'gplm'
formula(x, ...)

## S3 method for class 'gplm'
df.residual(object, ...)

## S3 method for class 'gplm'
summary(object, ...)

## S3 method for class 'gplm'
coef(object, ...)

## S3 method for class 'gplm'
residuals(object, ...)

## S3 method for class 'gplm'
fitted(object, ...)

Arguments

formula

A formula specifying the model to estimate.

data

A data.frame or matrix containing panel data. Without index, the panel must be balanced and ordered in long format \bold{Y}=(Y_1^\prime, \dots, Y_N^\prime)^\prime, Y_i = (Y_{i1}, \dots, Y_{iT})^\prime with Y_{it} = (y_{it}, x_{it}^\prime)^\prime. Otherwise, data must contain variables identifying the cross-sectional unit i and time period t of each observation.

groups

A numerical or character vector of length N that indicates the group membership of each cross-sectional unit i.

index

A character vector naming the cross-sectional unit i and time period t variables, in that order. Data are sorted by these variables; a character time index may cause errors. For a balanced panel already ordered in long format, index may be omitted if n_periods is supplied.

n_periods

The number of observed time periods T. May be omitted when index is supplied. Default is NULL.

method

The estimation method. Options are

"PLS"

Penalised least squares (PLS), recommended for (weakly) exogenous regressors (Mehrabani, 2023, sec. 2.2).

"PGMM"

Penalised generalised method of moments (PGMM), used with endogenous regressors. A matrix \bold{Z} of exogenous instruments must be supplied (Mehrabani, 2023, sec. 2.3).

Default is "PLS".

Z

A NT \times q matrix or data.frame of exogenous instruments, where q \geq p, \bold{Z}=(z_1^\prime, \dots, z_N^\prime)^\prime, z_i = (z_{i1}, \dots, z_{iT})^\prime and z_{it} is a q \times 1 vector. Z is only required when method = "PGMM" is selected. When using "PLS", the argument can be left empty or it is disregarded. Default is NULL.

global_coef

A character vector containing the variable names of explanatory variables whose coefficient is common to all cross-sectional units instead of group-specific (see Details). Requires method = "PLS". Default is NULL.

ind_coef

A character vector containing the variable names of explanatory variables whose coefficient is specific to each cross-sectional unit instead of group-specific (see Details). Requires method = "PLS". Default is NULL.

bias_correc

Logical. If TRUE, applies the split-panel jackknife bias correction of Dhaene and Jochmans (2015) to the slope parameters. Recommended for dynamic panels. When global_coef is supplied, group-specific and global coefficients are corrected jointly. The correction is skipped with a warning if the global coefficients are not identified on one half of the panel. Default is FALSE.

rho

A tuning parameter balancing the fitness and penalty terms in the IC. If left unspecified, the heuristic \rho = 0.07 \frac{\log(NT)}{\sqrt{NT}} of Mehrabani (2023, sec. 6) is used. We recommend the default.

verbose

Logical. If TRUE, messages are shown. Default is TRUE.

parallel

Logical. If TRUE, certain operations are parallelised across multiple cores. The number of workers defaults to all logical cores and can be set via RcppParallel::setThreadOptions() or the RCPP_PARALLEL_NUM_THREADS environment variable. Default is TRUE.

...

Additional arguments.

x

An object of class gplm.

object

An object of class gplm.

Details

Consider the grouped panel data model

y_{it} = \gamma_i^0 + \bold{\beta}^{0 \prime}_{i} \bold{x}_{it} + \epsilon_{it}, \quad i = 1, \dots, N, \; t = 1, \dots, T,

where y_{it} is the scalar dependent variable, \gamma_i^0 is an individual fixed effect, \bold{x}_{it} is a p \times 1 vector of (weakly) exogenous explanatory variables, and \epsilon_{it} denotes a zero-mean error. The coefficient vector \bold{\beta}_i^0 follows the observed group pattern

\bold{\beta}_i^0 = \sum_{k = 1}^K \bold{\alpha}_k^0 \bold{1} \{i \in G_k \},

with \cup_{k = 1}^K G_k = \{1, \dots, N\}, G_k \cap G_j = \emptyset, and \| \bold{\alpha}_k^0 - \bold{\alpha}_j^0 \| \neq 0 for any k \neq j, k,j = 1, \dots, K. The group structure G_1, \dots, G_K is determined by the argument groups.

Using PLS, the group-specific coefficients of group k, \, k = 1, \dots, K are obtained by OLS

\hat{\bold{\alpha}}_k = \left( \sum_{i \in G_k} \sum_{t = 1}^T \tilde{\bold{x}}_{it} \tilde{\bold{x}}_{it}^\prime \right)^{-1} \sum_{i \in G_k} \sum_{t = 1}^T \tilde{\bold{x}}_{it} \tilde{y}_{it},

The within transformation \tilde{a}_{it} = a_{it} - T^{-1} \sum_{t=1}^T a_{it}, a = \{y, \bold{x}\}, removes the individual fixed effects \gamma_i^0.

In case of PGMM, the slope coefficients are derived as

\hat{\alpha}_k = \left( \left[ \sum_{i \in G_k} T^{-1} \sum_{t = 1}^T \bold{z}_{it} \Delta \bold{x}_{it} \right]^\prime \bold{W}_k \left[ \sum_{i \in G_k} T^{-1} \sum_{t = 1}^T \bold{z}_{it} \Delta \bold{x}_{it} \right] \right)^{-1}

\quad \quad \left[ \sum_{i \in G_k} T^{-1} \sum_{t = 1}^T \bold{z}_{it} \Delta \bold{x}_{it} \right]^\prime \bold{W}_k \left[ \sum_{i \in G_k} T^{-1} \sum_{t = 1}^T \bold{z}_{it} \Delta y_{it} \right],

where \bold{W}_k is a q \times q symmetric positive-definite weight matrix and \Delta denotes the first-difference operator \Delta \bold{x}_{it} = \bold{x}_{it} - \bold{x}_{it-1} (first-difference transformation).

Variables named in global_coef obtain a coefficient \bold{\theta}^0 that is common to all cross-sectional units instead of a group-specific one, and variables named in ind_coef obtain a coefficient \bold{\psi}_i^0 specific to each unit, so that

y_{it} = \gamma_i^0 + \bold{\alpha}^{0 \prime}_{g_i} \bold{x}_{it} + \bold{\theta}^{0 \prime} \bold{w}_{it} + \bold{\psi}^{0 \prime}_{i} \bold{r}_{it} + \epsilon_{it},

where \bold{w}_{it} collects the global and \bold{r}_{it} the individual regressors. Both blocks carry no fusion penalty and are concentrated out of the criterion. The individual block is block-diagonal across units and is concentrated out first, so the two may be combined. At least one regressor must retain a group-specific coefficient.

Each \bold{\psi}_i^0 is identified from unit i's observations, so unit i needs more than p + q observed periods, and consistency requires T \to \infty. The individual block adds N q incidental parameters; the classification results in the references are derived without such a block. A regressor that is time-invariant within a unit is collinear with that unit's fixed effect and results in an error.

Value

An object of class gplm holding

model

a data.frame containing the dependent and explanatory variables as well as cross-sectional and time indices,

coefficients

a K \times p matrix of the group-specific parameter estimates,

coefficients_global

a 1 \times q matrix of the coefficients common to all cross-sectional units, for the q regressors named in global_coef. Only present if global_coef is supplied,

coefficients_ind

an N \times q matrix of the coefficients specific to each cross-sectional unit, for the q regressors named in ind_coef. Only present if ind_coef is supplied,

groups

a list containing (i) the total number of groups K and (ii) a vector of group memberships (g_1, \dots, g_N), where g_i = k if i is assigned to group k,

residuals

a vector of residuals of the demeaned model,

fitted

a vector of fitted values of the demeaned model,

args

a list of additional arguments,

IC

a list containing (i) the value of the IC and (ii) the MSE,

call

the function call.

A gplm object has print, summary, fitted, residuals, formula, df.residual, and coef S3 methods.

Author(s)

Paul Haimerl

References

Dhaene, G., & Jochmans, K. (2015). Split-panel jackknife estimation of fixed-effect models. The Review of Economic Studies, 82(3), 991-1030. doi:10.1093/restud/rdv007.

Mehrabani, A. (2023). Estimation and identification of latent group structures in panel data. Journal of Econometrics, 235(2), 1464-1482. doi:10.1016/j.jeconom.2022.12.002.

See Also

pagfl for jointly estimating the latent group structure and group-specific coefficients, grouped_tv_plm for the time-varying extension, and sim_DGP for simulating a suitable panel data set.

Examples

# Simulate a panel with a group structure
set.seed(1)
sim <- sim_DGP(N = 20, n_periods = 80, p = 2, n_groups = 3)
y <- sim$y
X <- sim$X
groups <- sim$groups
df <- cbind(y = c(y), X)

# Estimate the grouped panel data model
estim <- grouped_plm(y ~ ., data = df, groups = groups, n_periods = 80, method = "PLS")
summary(estim)

# Let's pass a panel data set with explicit cross-sectional and time indicators
i_index <- rep(1:20, each = 80)
t_index <- rep(1:80, 20)
df <- data.frame(y = c(y), X, i_index = i_index, t_index = t_index)
estim <- grouped_plm(
  y ~ .,
  data = df, index = c("i_index", "t_index"), groups = groups, method = "PLS"
)
summary(estim)

Grouped Time-varying Panel Data Model

Description

Estimate a time-varying panel data model subject to an observed group structure. Coefficient functions are homogeneous within groups but heterogeneous across groups. Time-varying coefficient functions are approximated as polynomial B-splines. The function supports both static and dynamic panel data models.

Usage

grouped_tv_plm(
  formula,
  data,
  groups,
  index = NULL,
  n_periods = NULL,
  d = 3,
  M = floor(length(y)^(1/7) - log(p)),
  lambda_smooth = 0,
  scale_smooth = FALSE,
  const_coef = NULL,
  global_coef = NULL,
  ind_coef = NULL,
  rho = 0.04 * log(N * n_periods)/sqrt(N * n_periods),
  verbose = TRUE,
  parallel = TRUE,
  ...
)

## S3 method for class 'tv_gplm'
summary(object, ...)

## S3 method for class 'tv_gplm'
formula(x, ...)

## S3 method for class 'tv_gplm'
df.residual(object, ...)

## S3 method for class 'tv_gplm'
print(x, ...)

## S3 method for class 'tv_gplm'
coef(object, ...)

## S3 method for class 'tv_gplm'
residuals(object, ...)

## S3 method for class 'tv_gplm'
fitted(object, ...)

Arguments

formula

A formula specifying the model to estimate.

data

A data.frame or matrix containing panel data. Without index, the panel must be balanced and ordered in long format \bold{Y}=(Y_1^\prime, \dots, Y_N^\prime)^\prime, Y_i = (Y_{i1}, \dots, Y_{iT})^\prime with Y_{it} = (y_{it}, \bold{x}_{it}^\prime)^\prime. Otherwise, data must contain variables identifying the cross-sectional unit i and time period t of each observation.

groups

A numerical or character vector of length N that indicates the group membership of each cross-sectional unit i.

index

A character vector naming the cross-sectional unit i and time period t variables, in that order. Data are sorted by these variables; a character time index may cause errors. For a balanced panel already ordered in long format, index may be omitted if n_periods is supplied.

n_periods

The number of observed time periods T. May be omitted when index is supplied. Default is NULL.

d

The polynomial degree of the B-splines. Default is 3.

M

The number of interior knots of the B-splines. The default is M = \max\{\lfloor n^{1/7} - \log(p_{\mathrm{TV}})\rfloor, 1\}, where n is the number of retained observations and p_{\mathrm{TV}} counts all time-varying regressors, including global and individual ones. In the balanced baseline model, this is the heuristic of Haimerl et al. (2026, sec. 4.1). Package M is the paper's M^*; the spline basis dimension is M + d + 1. The full knot sequence has M + 2d + 2 knots, including the repeated boundary knots.

lambda_smooth

A numeric value \geq 0 controlling the O'Sullivan curvature penalty on time-varying coefficient functions (see Details). lambda_smooth = 0 gives unpenalised least squares; positive values require d \geq 2. Time-constant coefficients in const_coef are not penalised. Default is 0.

scale_smooth

Logical. If TRUE, the curvature penalty of each time-varying regressor is weighted by the regressor's mean square, so that it does not depend on the regressor's units (see Details). No effect if lambda_smooth = 0. Default is FALSE.

const_coef

A character vector containing the variable names of explanatory variables that enter with time-constant coefficients.

global_coef

A character vector containing the variable names of explanatory variables whose coefficient is common to all cross-sectional units instead of group-specific (see Details). A variable appearing in both const_coef and global_coef obtains a global and time-constant coefficient. Default is NULL.

ind_coef

A character vector containing the variable names of explanatory variables whose coefficient is specific to each cross-sectional unit rather than a group (see Details). A variable appearing in both const_coef and ind_coef obtains an individual and time-constant coefficient. Default is NULL.

rho

The tuning parameter balancing the fit and complexity terms in the IC. The default \rho = 0.04 \frac{\log(NT)}{\sqrt{NT}} follows Haimerl et al. (2026, sec. 3.3, eq. 3.1). Here T is the number of distinct retained time periods, including for an unbalanced panel. We recommend the default.

verbose

Logical. If TRUE, messages are shown. Default is TRUE.

parallel

Logical. If TRUE, certain operations are parallelised across multiple cores. The number of workers defaults to all logical cores and can be set via RcppParallel::setThreadOptions() or the RCPP_PARALLEL_NUM_THREADS environment variable. Default is TRUE.

...

Additional arguments.

object

An object of class tv_gplm.

x

An object of class tv_gplm.

Details

Consider the time-varying panel data model of Haimerl et al. (2026, sec. 2.1, eqs. 2.1–2.3), with known groups

y_{it} = \gamma_i^0 + \bold{\beta}^{0\prime}_{i} (t/T) \bold{x}_{it} + \epsilon_{it}, \quad i = 1, \dots, N, \; t = 1, \dots, T,

where y_{it} is the scalar dependent variable, \gamma_i^0 is an individual fixed effect, \bold{x}_{it} is a p \times 1 vector of explanatory variables, and \epsilon_{it} is a zero-mean error. The p-dimensional coefficient vector \bold{\beta}_{i}^0 (t/T) contains smooth functions of time and follows the observed group pattern

\bold{\beta}_i^0 \left(\frac{t}{T} \right) = \sum_{k = 1}^K \bold{\alpha}_k^0 \left( \frac{t}{T} \right) \bold{1} \{i \in G_k \},

with \cup_{k = 1}^K G_k = \{1, \dots, N\}, G_k \cap G_j = \emptyset, and \sup_{v \in [0,1]} \| \bold{\alpha}_k(v) - \bold{\alpha}_j(v) \| \neq 0 for any k \neq j, k,j = 1, \dots, K. The group structure G_1, \dots, G_K is determined by the argument groups. Estimation requires suitable regressor–error orthogonality and regularity conditions; see the paper's Section 3 and Appendix A. Dynamic specifications can retain Nickell bias; this function does not apply a time-varying bias correction (sec. 3.2).

The time-varying coefficient functions in \bold{\alpha}_k (t/T) and, in turn, \bold{\beta}_i (t/T) are estimated as polynomial B-splines. To this end, let \bold{b}(v) denote a M + d +1 vector of polynomial basis functions with the polynomial degree d and M interior knots. The displays use the paper's t/T notation. The package places boundary knots at the first and last retained time indices, corresponding to v = (t - 1)/(T - 1); finite-sample knot locations therefore differ from the paper's convention. \bold{\alpha}_k^0 (t/T) is approximated by forming linear combinations of the basis functions \bold{\alpha}_k^0 (t/T) \approx \bold{\Xi}_k^{0 \prime} \bold{b} (t/T), where \bold{\Xi}_k^{0} is a group-specific (M + d + 1) \times p matrix of spline control points.

To estimate \bold{\Xi}_k^{0}, we expand the explanatory variables in the spline basis, resulting in the (M + d + 1)p \times 1 regressor vector \bold{z}_{it} = \bold{x}_{it} \otimes \bold{b}(t/T). Subsequently, the DGP can be reformulated as

y_{it} = \gamma_i^0 + \bold{\pi}_{i}^{0 \prime} \bold{z}_{it} + u_{it},

where \bold{\pi}_i^0 = \text{vec}(\bold{\Pi}_i^0) and \bold{\Xi}_k^0 = \bold{\Pi}_i^0 if i \in G_k. Here u_{it} = \epsilon_{it} + \eta_{it}, with sieve approximation error in the response equation \eta_{it} = [\bold{\beta}_i^0(t/T) - \bold{\Pi}_i^{0\prime}\bold{b}(t/T)]^\prime \bold{x}_{it} (Haimerl et al., 2026, sec. 2.2, eqs. 2.4–2.5). For the balanced baseline model, we obtain \hat{\bold{\xi}}_k = \text{vec}( \hat{\bold{\Xi}}_k) by

\hat{\bold{\xi}}_k = \left( \sum_{i \in G_k} \sum_{t = 1}^T \tilde{\bold{z}}_{it} \tilde{\bold{z}}_{it}^\prime \right)^{-1} \sum_{i \in G_k} \sum_{t = 1}^T \tilde{\bold{z}}_{it} \tilde{y}_{it}.

The within transformation \tilde{a}_{it} = a_{it} - T^{-1} \sum_{t = 1}^T a_{it}, a = \{y, \bold{z}\}, removes the fixed effect \gamma_i^0. The coefficient function is \hat{\bold{\alpha}}_k (t/T) = \hat{\bold{\Xi}}_k^{\prime} \bold{b} (t/T) (Haimerl et al., 2026, sec. 2.2, unnumbered post-Lasso estimator). The inverse formulas are interpreted on the identified coefficient space, using a generalised inverse when needed. A grouped time-varying intercept has an unidentified constant level after demeaning; its reported curve is centred. Smoothing does not identify that level.

Setting lambda_smooth > 0 adds an O'Sullivan smoothness penalty (O'Sullivan 1986; Wand & Ormerod 2008) to the least squares problem, yielding the penalised estimator

\hat{\bold{\xi}}_k = \arg\min_{\bold{\xi}} \; \sum_{i \in G_k} \sum_{t = 1}^T \left( \tilde{y}_{it} - \tilde{\bold{z}}_{it}^\prime \bold{\xi} \right)^2 + \lambda \sum_{j = 1}^p \bold{\xi}_{(j)}^\prime \bold{\Omega} \, \bold{\xi}_{(j)} = \left( \sum_{i \in G_k} \sum_{t = 1}^T \tilde{\bold{z}}_{it} \tilde{\bold{z}}_{it}^\prime + \lambda \bold{P} \right)^{-1} \sum_{i \in G_k} \sum_{t = 1}^T \tilde{\bold{z}}_{it} \tilde{y}_{it},

where \lambda = lambda_smooth, \bold{\xi}_{(j)} denotes the (M + d + 1)-dimensional block of spline control points belonging to the j-th time-varying coefficient, and \bold{P} = \bold{I}_p \otimes \bold{\Omega} (padded with zeros for time-constant coefficients, which remain unpenalised). The penalty matrix \bold{\Omega} = \int_0^1 \bold{b}^{\prime \prime}(v) \bold{b}^{\prime \prime}(v)^\prime \, dv is computed exactly on the normalised time domain v = (t - 1)/(T - 1) \in [0,1], so that \bold{\xi}_{(j)}^\prime \bold{\Omega} \bold{\xi}_{(j)} = \int_0^1 (\alpha_{k,j}^{\prime \prime}(v))^2 dv equals the integrated squared curvature of the j-th coefficient function. Constructing the penalty on the raw time index would introduce a factor of (T-1)^{-3}. Since the null space of \bold{\Omega} consists of all linear functions, the coefficient functions approach linear functions of v as lambda_smooth \to \infty. The curvature penalty requires d \geq 2. Rescaling a regressor by c \neq 0 rescales its coefficient function by 1/c and its curvature penalty by 1/c^2. With scale_smooth = TRUE, the j-th penalty term is therefore multiplied by the regressor's mean square over the n retained observations, q_j = n^{-1} \sum_{i,t} x_{it,j}^2, so that \bold{P} = \text{diag}(q_1, \dots, q_p) \otimes \bold{\Omega} (Chiang 2005, eq. 2.1). The penalised fit is then invariant to the units of the regressors. An intercept has weight one; global and individual blocks are weighted in the same way.

Mixed global, group-specific and individual coefficients are discussed by Haimerl et al. (2026, Supplement S4.1), and mixed time-varying and time-constant coefficients in Supplement S4.2. The curvature penalties and effective degrees of freedom are package extensions whose asymptotic properties are not established in the paper.

Variables named in ind_coef obtain a coefficient that is specific to each cross-sectional unit, \bold{\psi}_i(t/T), instead of a group-specific one. The model becomes

y_{it} = \gamma_i^0 + \bold{\alpha}^{0 \prime}_{g_i} (t/T) \bold{x}_{it} + \bold{\psi}^{0 \prime}_{i} (t/T) \bold{r}_{it} + \epsilon_{it},

where \bold{r}_{it} collects the individual regressors. The individual spline block uses the same curvature penalty as the grouped blocks, with lambda_smooth applied once per unit. The block is block-diagonal across units, so it is concentrated out first; global_coef may be supplied alongside it. At least one regressor must retain a grouped coefficient; it may be time-constant if a global or individual coefficient is time-varying.

An individual time-varying regressor that is time-invariant within a unit identifies only the shape of \bold{\psi}_i(t/T), since unit i's fixed effect absorbs the level; such curves are centred. An individual time-varying intercept is allowed, but it cannot be combined with a grouped intercept, which it would absorb. There is one individual coefficient block per unit, estimated from that unit's observations; consistent estimation of individual curves requires a growing time dimension. The paper's baseline classification results are derived without this block.

Variables named in global_coef obtain a coefficient that is common to all cross-sectional units, \bold{\theta}(t/T), instead of a group-specific one. The model becomes

y_{it} = \gamma_i^0 + \bold{\alpha}^{0 \prime}_{g_i} (t/T) \bold{x}_{it} + \bold{\theta}^{0 \prime} (t/T) \bold{w}_{it} + \epsilon_{it},

where \bold{w}_{it} collects the global regressors. At least one regressor must retain a grouped coefficient. A global spline block can receive the same curvature penalty as the grouped blocks, with lambda_smooth applied once. For a regressor that is constant within each unit, the fixed effects absorb the level of its global coefficient function; only its shape is identified. Unidentified constant-level combinations are removed before solving. For a regressor that varies within units, the level may be identified. Specifications in which the global coefficients are not identified at all, for instance a global intercept alongside a grouped intercept, result in an error.

For an unbalanced panel, sums and within means use each unit's observed periods (Haimerl et al., 2026, Supplement S4.3). Group-specific coefficient functions are reported only between each group's earliest and latest observations, with NA outside that span. Pooling and interpolation require sufficient information in the observed design. When lambda_smooth > 0, the penalty covers the full observation window and can regularise curvature that the observed data do not identify; its linear null space still requires identification or normalisation.

Value

An object of class tv_gplm holding

model

a data.frame containing the dependent and explanatory variables as well as cross-sectional and time indices,

coefficients

Let p^{(1)} denote the number of grouped time-varying and p^{(2)} the number of grouped time-constant coefficients. A list holding (i) a T \times p^{(1)} \times K array of the group-specific functional coefficients and (ii) a K \times p^{(2)} matrix of time-constant estimates. If global_coef is supplied, the list additionally holds (iii) a T \times p^{(3)} matrix of the global functional coefficients and (iv) a 1 \times p^{(4)} matrix of global time-constant estimates, for the p^{(3)} global time-varying and p^{(4)} global time-constant regressors. If ind_coef is supplied, tv_ind and const_ind contain a T \times q_{\mathrm{TV}} \times N array and an N \times q_{\mathrm{C}} matrix for the individual time-varying and time-constant regressors, respectively; absent blocks are omitted.

groups

a list containing (i) the total number of groups K and (ii) a vector of group memberships G = (g_1, \dots, g_N), where g_i = k if i is part of group k,

residuals

a vector of residuals of the demeaned model,

fitted

a vector of fitted values on the original outcome scale, including the unit means removed by the within transformation,

args

a list of additional arguments,

IC

a list containing (i) the value of the IC and (ii) the MSE,

edf_global

the effective degrees of freedom added by the global block after the individual and grouped smoothers. Only present if global_coef is supplied and lambda_smooth > 0,

edf

a vector of effective degrees of freedom added by each grouped block after the individual smoother. Only present if lambda_smooth > 0,

edf_ind

a named vector of individual smoother degrees of freedom, one per unit. Only present if ind_coef is supplied and lambda_smooth > 0. Its sum, plus the grouped and global contributions when present, is the joint model EDF excluding fixed effects. IC and residual degrees of freedom retain nominal coefficient counts,

call

the function call.

An object of class tv_gplm has print, summary, fitted, residuals, formula, df.residual, and coef S3 methods.

Author(s)

Paul Haimerl

References

Chiang, C.-T. (2005). Comparisons between simultaneous and componentwise splines for varying coefficient models. Annals of the Institute of Statistical Mathematics, 57(4), 637-653. doi:10.1007/BF02915430.

Haimerl, P., Smeekes, S., & Wilms, I. (2026). Estimation of latent group structures in time-varying panel data models. The Econometrics Journal. doi:10.1093/ectj/utag034.

O'Sullivan, F. (1986). A statistical perspective on ill-posed inverse problems. Statistical Science, 1(4), 502-518. doi:10.1214/ss/1177013525.

Wand, M. P., & Ormerod, J. T. (2008). On semiparametric regression with O'Sullivan penalized splines. Australian & New Zealand Journal of Statistics, 50(2), 179-198. doi:10.1111/j.1467-842X.2008.00507.x.

See Also

fuse_time for jointly estimating the latent group structure and group-specific time-varying coefficients, grouped_plm for the static (time-invariant) counterpart, and sim_tv_DGP for simulating a suitable time-varying panel data set.

Examples

# Simulate a time-varying panel with a trend and a group pattern
set.seed(1)
sim <- sim_tv_DGP(N = 10, n_periods = 50, intercept = TRUE, p = 2)
df <- data.frame(y = c(sim$y), X = sim$X)
groups <- sim$groups

# Estimate the time-varying grouped panel data model
estim <- grouped_tv_plm(y ~ ., data = df, n_periods = 50, groups = groups)
summary(estim)


Pairwise Adaptive Group Fused Lasso

Description

Estimate a panel data model with a latent group structure using the pairwise adaptive group fused Lasso (PAGFL) of Mehrabani (2023). PAGFL jointly identifies the group structure and group-specific slope parameters. The function supports both static and dynamic panels, with or without endogenous regressors.

Usage

pagfl(
  formula,
  data,
  index = NULL,
  n_periods = NULL,
  lambda,
  method = "PLS",
  Z = NULL,
  min_group_frac = 0.05,
  global_coef = NULL,
  ind_coef = NULL,
  bias_correc = FALSE,
  kappa = 2,
  max_iter = 10000,
  tol_convergence = 1e-08,
  tol_group = 0.001,
  rho = 0.07 * log(N * n_periods)/sqrt(N * n_periods),
  varrho = max(sqrt(5 * N * n_periods * p)/log(N * n_periods * p) - 7, 1),
  verbose = TRUE,
  parallel = TRUE,
  ...
)

## S3 method for class 'pagfl'
print(x, ...)

## S3 method for class 'pagfl'
formula(x, ...)

## S3 method for class 'pagfl'
df.residual(object, ...)

## S3 method for class 'pagfl'
summary(object, ...)

## S3 method for class 'pagfl'
coef(object, ...)

## S3 method for class 'pagfl'
residuals(object, ...)

## S3 method for class 'pagfl'
fitted(object, ...)

Arguments

formula

A formula specifying the model to estimate.

data

A data.frame or matrix containing panel data. Without index, the panel must be balanced and ordered in long format \bold{Y}=(Y_1^\prime, \dots, Y_N^\prime)^\prime, Y_i = (Y_{i1}, \dots, Y_{iT})^\prime with Y_{it} = (y_{it}, \bold{x}_{it}^\prime)^\prime. Otherwise, data must contain variables identifying the cross-sectional unit i and time period t of each observation.

index

A character vector naming the cross-sectional unit i and time period t variables, in that order. Data are sorted by these variables; a character time index may cause errors. For a balanced panel already ordered in long format, index may be omitted if n_periods is supplied.

n_periods

The number of observed time periods T. May be omitted when index is supplied. Default is NULL.

lambda

The tuning parameter determining the strength of the penalty term. Either a single \lambda or a vector of candidate values can be passed. If a vector is supplied, a BIC-type IC automatically selects the best-fitting \lambda value.

method

The estimation method. Options are

"PLS"

Penalised least squares (PLS), recommended for (weakly) exogenous regressors (Mehrabani, 2023, sec. 2.2).

"PGMM"

Penalised generalised method of moments (PGMM), used with endogenous regressors. A matrix \bold{Z} of exogenous instruments must be supplied (Mehrabani, 2023, sec. 2.3).

Default is "PLS".

Z

A NT \times q matrix or data.frame of exogenous instruments, where q \geq p, \bold{Z}=(z_1^\prime, \dots, z_N^\prime)^\prime, z_i = (z_{i1}, \dots, z_{iT})^\prime and z_{it} is a q \times 1 vector. Z is only required when method = "PGMM" is selected. When using "PLS", the argument can be left empty or it is disregarded. Default is NULL.

min_group_frac

The minimum group size as a fraction of N. If a group falls below this threshold, its members are assigned to the remaining groups according to the MSE. Default is 0.05.

global_coef

A character vector containing the variable names of explanatory variables whose coefficient is common to all cross-sectional units instead of group-specific (see Details). Requires method = "PLS". Default is NULL.

ind_coef

A character vector containing the variable names of explanatory variables whose coefficient is specific to each cross-sectional unit instead of group-specific (see Details). Requires method = "PLS". Default is NULL.

bias_correc

Logical. If TRUE, applies the split-panel jackknife bias correction of Dhaene and Jochmans (2015) to the slope parameters. Recommended for dynamic panels. When global_coef is supplied, group-specific and global coefficients are corrected jointly. The correction is skipped with a warning if the global coefficients are not identified on one half of the panel. Default is FALSE.

kappa

A non-negative weight used to obtain the adaptive penalty weights. Default is 2.

max_iter

The maximum number of iterations for the ADMM estimation algorithm. Default is 1*10^4.

tol_convergence

The tolerance limit for the stopping criterion of the iterative ADMM estimation algorithm. Default is 1*10^{-8}.

tol_group

The tolerance limit for within-group differences. Two individuals i, j are assigned to the same group if the Frobenius norm of their coefficient vector difference is below this threshold. Default is 1*10^{-3}.

rho

The tuning parameter balancing the fitness and penalty terms in the IC that determines the penalty parameter \lambda. If left unspecified, the heuristic \rho = 0.07 \frac{\log(NT)}{\sqrt{NT}} of Mehrabani (2023, sec. 6) is used. We recommend the default.

varrho

The non-negative Lagrangian ADMM penalty parameter. For PLS, the \varrho value is trivial. However, for PGMM, small values lead to slow convergence. If left unspecified, the default heuristic \varrho = \max(\frac{\sqrt{5NTp}}{\log(NTp)}-7, 1) is used, where p counts only the regressors that keep a group-specific coefficient, since the ADMM operates on those alone. Declaring a variable in global_coef therefore changes the default.

verbose

Logical. If TRUE, messages are shown. Default is TRUE.

parallel

Logical. If TRUE, computation is parallelised across multiple cores. When lambda is a grid with more than two values, the search over \lambda is dispatched in parallel, with each penalty value fitted independently from a cold start; otherwise certain inner per-iteration operations of the ADMM algorithm are parallelised via RcppParallel. Results are numerically identical to the sequential path. The number of workers defaults to all logical cores and can be set via RcppParallel::setThreadOptions() or the RCPP_PARALLEL_NUM_THREADS environment variable. Default is TRUE.

...

Additional arguments.

x

An object of class pagfl.

object

An object of class pagfl.

Details

Consider the panel data model

y_{it} = \gamma_i^0 + \bold{\beta}^{0 \prime}_{i} \bold{x}_{it} + \epsilon_{it}, \quad i = 1, \dots, N, \; t = 1, \dots, T,

where y_{it} is the scalar dependent variable, \gamma_i^0 is an individual fixed effect, \bold{x}_{it} is a p \times 1 vector of weakly exogenous explanatory variables, and \epsilon_{it} is a zero-mean error. The coefficient vector \bold{\beta}_i^0 follows the latent group pattern

\bold{\beta}_i^0 = \sum_{k = 1}^K \bold{\alpha}_k^0 \bold{1} \{i \in G_k^0 \},

with \cup_{k = 1}^K G_k^0 = \{1, \dots, N\}, G_k^0 \cap G_j^0 = \emptyset, and \| \bold{\alpha}_k^0 - \bold{\alpha}_j^0 \| \neq 0 for any k \neq j, k,j = 1, \dots, K.

The PLS method jointly estimates the latent group structure and group-specific coefficients by minimising the criterion

Q_{NT} (\bold{\beta}, \lambda) = \frac{1}{T} \sum^N_{i=1} \sum^{T}_{t=1}(\tilde{y}_{it} - \bold{\beta}^\prime_i \tilde{\bold{x}}_{it})^2 + \frac{\lambda}{N} \sum_{i = 1}^{N - 1} \sum_{j=i+1}^N \dot{\omega}_{ij} \| \bold{\beta}_i - \bold{\beta}_j \|

with respect to \bold{\beta} = (\bold{\beta}_1^\prime, \dots, \bold{\beta}_N^\prime)^\prime. The within transformation \tilde{a}_{it} = a_{it} - T^{-1} \sum_{t = 1}^T a_{it}, a = \{y, \bold{x}\}, removes the individual fixed effects \gamma_i^0. \lambda is the penalty tuning parameter, and \dot{\omega}_{ij} denotes adaptive penalty weights (Mehrabani, 2023, eq. 2.6). \| \cdot \| denotes the Frobenius norm. The adaptive weights \dot{w}_{ij} are obtained by a preliminary individual least squares estimation. The criterion is minimised using an alternating direction method of multipliers (ADMM) algorithm (Mehrabani, 2023, sec. 5.1).

PGMM uses instruments Z for endogenous regressors. Under PGMM, \bold{\beta} is estimated by minimising

Q_{NT}(\bold{\beta}, \lambda) = \sum^N_{i = 1} \left[ \frac{1}{T} \sum_{t=1}^T \bold{z}_{it} (\Delta y_{it} - \bold{\beta}^\prime_i \Delta \bold{x}_{it}) \right]^\prime \bold{W}_i \left[\frac{1}{T} \sum_{t=1}^T \bold{z}_{it}(\Delta y_{it} - \bold{\beta}^\prime_i \Delta \bold{x}_{it}) \right]

\quad + \frac{\lambda}{N} \sum_{i = 1}^{N - 1} \sum_{j=i+1}^N \ddot{\omega}_{ij} \| \bold{\beta}_i - \bold{\beta}_j \|.

\ddot{\omega}_{ij} are obtained by an initial GMM estimation. \Delta gives the first-difference operator \Delta y_{it} = y_{it} - y_{i t-1}. \bold{W}_i represents a data-driven q \times q weight matrix. We refer to Mehrabani (2023, eq. 2.10) for more details. The criterion is minimised using an ADMM algorithm (Mehrabani, 2023, sec. 5.2).

Two individuals are assigned to the same group if \| \hat{\bold{\beta}}_i - \hat{\bold{\beta}}_j \| \leq \epsilon_{\text{tol}} (and hence \hat{\bold{\alpha}}_k = \hat{\bold{\beta}}_i = \hat{\bold{\beta}}_j for some k = 1, \dots, \hat{K}), where \epsilon_{\text{tol}} is determined by tol_group. Subsequently, the estimated number of groups \hat{K} and group structure follow by examining the number of distinct elements in \hat{\bold{\beta}}. Given an estimated group structure, it is straightforward to obtain post-Lasso estimates using group-wise least squares or GMM (see grouped_plm).

Variables named in ind_coef obtain a coefficient \bold{\psi}_i^0 that is specific to each cross-sectional unit, so that

y_{it} = \gamma_i^0 + \bold{\beta}^{0 \prime}_{i} \bold{x}_{it} + \bold{\psi}^{0 \prime}_{i} \bold{r}_{it} + \epsilon_{it},

where \bold{r}_{it} collects the individual regressors. The individual block carries no fusion penalty and is concentrated out of the criterion. The block is block-diagonal across units, so it is concentrated out first; global_coef may be supplied alongside it. At least one regressor must retain a group-specific coefficient.

Each \bold{\psi}_i^0 is identified from unit i's observations, so unit i needs more than p + q observed periods, and consistency requires T \to \infty. The individual block adds N q incidental parameters; the classification results in the references are derived without such a block. A regressor that is time-invariant within a unit is collinear with that unit's fixed effect and results in an error.

Variables named in global_coef obtain a coefficient \bold{\theta}^0 that is common to all cross-sectional units instead of a group-specific one, so that

y_{it} = \gamma_i^0 + \bold{\beta}^{0 \prime}_{i} \bold{x}_{it} + \bold{\theta}^{0 \prime} \bold{w}_{it} + \epsilon_{it},

where \bold{w}_{it} collects the global regressors. The global block carries no fusion penalty and is concentrated out of the criterion, imposing a common coefficient across units. At least one regressor must retain a group-specific coefficient. Specifications in which the global coefficients are not identified, for instance a global regressor that every unit can reproduce with its own coefficients, result in an error.

To select \lambda, pass a logarithmically spaced grid with a lower limit near 0 and an upper limit that yields a fully homogeneous panel. A BIC-type information criterion selects a value from the grid.

Value

An object of class pagfl holding

model

a data.frame containing the dependent and explanatory variables as well as cross-sectional and time indices,

coefficients

a \hat{K} \times p matrix of the post-Lasso group-specific parameter estimates,

coefficients_global

a 1 \times q matrix of the coefficients common to all cross-sectional units, for the q regressors named in global_coef. Only present if global_coef is supplied,

coefficients_ind

an N \times q matrix of the coefficients specific to each cross-sectional unit, for the q regressors named in ind_coef. Only present if ind_coef is supplied,

groups

a list containing (i) the total number of groups \hat{K} and (ii) a vector of estimated group memberships (\hat{g}_1, \dots, \hat{g}_N), where \hat{g}_i = k if i is assigned to group k,

residuals

a vector of residuals of the demeaned model,

fitted

a vector of fitted values of the demeaned model,

args

a list of additional arguments,

IC

a list containing (i) the value of the IC, (ii) the employed tuning parameter \lambda, (iii) the MSE, and (iv) lambda_grid, a matrix reporting \lambda, the IC, the MSE, and the implied number of groups for each candidate \lambda, with the selected \lambda marked by an asterisk,

convergence

a list containing (i) a logical variable indicating if convergence was achieved and (ii) the number of executed ADMM algorithm iterations,

call

the function call.

A pagfl object has print, summary, fitted, residuals, formula, df.residual, and coef S3 methods.

Author(s)

Paul Haimerl

References

Dhaene, G., & Jochmans, K. (2015). Split-panel jackknife estimation of fixed-effect models. The Review of Economic Studies, 82(3), 991-1030. doi:10.1093/restud/rdv007.

Mehrabani, A. (2023). Estimation and identification of latent group structures in panel data. Journal of Econometrics, 235(2), 1464-1482. doi:10.1016/j.jeconom.2022.12.002.

See Also

fuse_time for the time-varying extension of the procedure, grouped_plm for estimation given an observed group structure, and sim_DGP for simulating a panel data set with a latent group structure.

Examples

# Simulate a panel with a group structure
set.seed(1)
sim <- sim_DGP(N = 20, n_periods = 80, p = 2, n_groups = 3)
y <- sim$y
X <- sim$X
df <- cbind(y = c(y), X)

# Run the PAGFL procedure
estim <- pagfl(y ~ ., data = df, n_periods = 80, lambda = 0.5, method = "PLS")
summary(estim)

# Let's pass a panel data set with explicit cross-sectional and time indicators
i_index <- rep(1:20, each = 80)
t_index <- rep(1:80, 20)
df <- data.frame(y = c(y), X, i_index = i_index, t_index = t_index)
estim <- pagfl(
  y ~ .,
  data = df, index = c("i_index", "t_index"), lambda = 0.5, method = "PLS"
)
summary(estim)

Simulate a Panel With a Group Structure in the Slope Coefficients

Description

Simulate a static or dynamic panel with group-specific slope coefficients, exogenous or endogenous regressors, and optional AR(1) or GARCH(1,1) innovations.

Usage

sim_DGP(
  N = 50,
  n_periods = 40,
  p = 2,
  n_groups = 3,
  group_proportions = NULL,
  error_spec = "iid",
  dynamic = FALSE,
  dyn_panel = lifecycle::deprecated(),
  q = NULL,
  alpha_0 = NULL
)

Arguments

N

The number of cross-sectional units. Default is 50.

n_periods

The number of simulated time periods T. Default is 40.

p

The number of explanatory variables. Default is 2.

n_groups

The number of groups K. Default is 3.

group_proportions

A numeric vector of length n_groups indicating the size of each group as a fraction of N. If NULL, group sizes are as close to N / K as possible. Default is NULL.

error_spec

Error specification. Options are

"iid"

for iid errors.

"AR"

for an AR(1) error process with an autoregressive coefficient of 0.5.

"GARCH"

for a GARCH(1,1) error process with a 0.05 constant, a 0.05 ARCH, and a 0.9 GARCH coefficient.

Default is "iid".

dynamic

Logical. If TRUE, the panel includes one stationary autoregressive lag of y_{it} as an explanatory variable (see Details for the AR coefficient). Default is FALSE.

dyn_panel

[Deprecated] Use dynamic instead.

q

The number of exogenous instruments when a panel with endogenous regressors is to be simulated. If a panel data set with exogenous regressors is to be generated, pass NULL. Default is NULL.

alpha_0

A K \times p matrix of group-specific coefficients. If dynamic = TRUE, the first column represents the stationary AR coefficient. If NULL, the coefficients are drawn randomly (see Details). Default is NULL.

Details

The scalar dependent variable y_{it} is generated according to the panel data model

y_{it} = \gamma_i + \bold{\beta}_i^\prime \bold{x}_{it} + u_{it}, \quad i = 1, \dots, N, \quad t = 1, \dots, T.

\gamma_i represents an individual fixed effect and \bold{x}_{it} a p \times 1 vector of regressors. The individual slope coefficient vectors \bold{\beta}_i follow the group structure

\bold{\beta}_i = \sum_{k = 1}^K \bold{\alpha}_k \bold{1} \{i \in G_k\},

with \cup_{k = 1}^K G_k = \{1, \dots, N\}, G_k \cap G_j = \emptyset, and \| \bold{\alpha}_k - \bold{\alpha}_j \| \neq 0 for any k \neq j, k,j = 1, \dots, K. The total number of groups K is determined by n_groups.

If a panel data set with exogenous regressors is generated (set q = NULL), the explanatory variables are simulated according to

x_{it,j} = 0.2 \gamma_i + e_{it,j}, \quad \gamma_i,e_{it,j} \sim i.i.d. N(0, 1), \quad j = 1, \dots, p,

where e_{it,j} denotes a series of innovations. \gamma_i and e_i are independent of each other.

If alpha_0 = NULL, the group-level slope parameters \bold{\alpha}_{k} are drawn from \sim Unif[-2, 2].

If dynamic = TRUE, x_{it,j} = e_{it,j}. When alpha_0 = NULL, the AR coefficients \rho_i are drawn uniformly from (-0.99, 0.99). The outcome follows

y_{it} = \rho_i y_{i,t-1} + \sum_j \beta_{ij} x_{it,j} + (1 - \rho_i)\gamma_i + u_{it}.

The first lag is y_{i0} = \sum_j \beta_{ij}x_{i0,j} + \gamma_i + u_{i0}. The pre-period x_{i0,j} and u_{i0} are independent standard normal draws for all q and error_spec values. \gamma_i corresponds to \eta_i in Mehrabani (2023). We refer to Mehrabani (2023, sec. 6) for details.

When specifying an endogenous panel (set q to q \geq p), the e_{it,j} correlate with the cross-sectional innovations u_{it} by a magnitude of 0.5 to produce endogenous regressors (\text{E}(u | \bold{X} ) \neq 0). However, the endogenous regressors can be accounted for by exploiting the q instruments in \bold{Z}, for which \text{E}(u| \bold{Z}) = 0 holds. The instruments and the first-stage coefficients are generated in the same fashion as \bold{X} and \bold{\alpha} when q = NULL.

The function nests, among others, the DGPs employed in the simulation study of Mehrabani (2023, sec. 6).

Value

A list holding

alpha

the K \times p matrix of group-specific slope parameters. If dynamic = TRUE, the first column holds the AR coefficient.

groups

a vector indicating the group memberships (g_1, \dots, g_N), where g_i = k if i \in group k.

y

a NT \times 1 vector of the dependent variable, with \bold{y}=( \bold{y}_1, \dots, \bold{y}_N)^\prime, \bold{y}_i = (y_{i1}, \dots, y_{iT})^\prime and the scalar y_{it}.

X

a NT \times p matrix of explanatory variables, with \bold{X}=(\bold{X}_1^\prime, \dots, \bold{X}_N^\prime)^\prime, \bold{X}_i = (\bold{x}_{i1}, \dots, \bold{x}_{iT})^\prime and the p \times 1 vector \bold{x}_{it}.

Z

a NT \times q matrix of instruments, where q \geq p, \bold{Z}=(\bold{Z}_1^\prime, \dots, \bold{Z}_N^\prime)^\prime, \bold{Z}_i = (\bold{z}_{i1}, \dots, \bold{z}_{iT})^\prime and \bold{z}_{it} is a q \times 1 vector. If a panel with exogenous regressors is generated (q = NULL), \bold{Z} equals NULL.

data

a NT \times (p + 1) data.frame of the outcome and p explanatory variables.

Author(s)

Paul Haimerl

References

Mehrabani, A. (2023). Estimation and identification of latent group structures in panel data. Journal of Econometrics, 235(2), 1464-1482. doi:10.1016/j.jeconom.2022.12.002.

See Also

sim_tv_DGP for simulating a time-varying panel data set, pagfl for jointly estimating the latent group structure and group-specific coefficients, and grouped_plm for estimation given an observed group structure.

Examples

# Simulate DGP 1 from Mehrabani (2023, sec. 6)
set.seed(1)
alpha_0_DGP1 <- matrix(c(0.4, 1, 1.6, 1.6, 1, 0.4), ncol = 2)
DGP1 <- sim_DGP(
  N = 50, n_periods = 20, p = 2, n_groups = 3,
  group_proportions = c(.4, .3, .3), alpha_0 = alpha_0_DGP1
)

Simulate a Time-varying Panel With a Group Structure in the Slope Coefficients

Description

Simulate a time-varying panel with group-specific slope coefficients and optional AR(1) innovations.

Usage

sim_tv_DGP(
  N = 50,
  n_periods = 40,
  intercept = TRUE,
  p = 1,
  n_groups = 3,
  d = 3,
  dynamic = FALSE,
  group_proportions = NULL,
  error_spec = "iid",
  locations = NULL,
  scales = NULL,
  polynomial_coef = NULL,
  sd_error = 1
)

Arguments

N

The number of cross-sectional units. Default is 50.

n_periods

The number of simulated time periods T. Default is 40.

intercept

Logical. If TRUE, a time-varying intercept is generated. Default is TRUE.

p

The total number of coefficient functions, including the optional intercept and lagged outcome. When both options are enabled, use p \geq 3 (see Details). Default is 1.

n_groups

The number of groups K. Default is 3.

d

The polynomial degree used to construct the time-varying coefficients. Default is 3.

dynamic

Logical. If TRUE, the panel includes the lagged outcome as a regressor. Default is FALSE.

group_proportions

A numeric vector of length n_groups indicating the size of each group as a fraction of N. If NULL, groups are as equal in size as possible. Default is NULL.

error_spec

Error specification. Options are

"iid"

for iid errors.

"AR"

for an AR(1) error process with an autoregressive coefficient of 0.5.

Default is "iid".

locations

A p \times K matrix of location parameters of a logistic distribution function used to construct the time-varying coefficients. If left empty, the location parameters are drawn randomly. Default is NULL.

scales

A p \times K matrix of scale parameters of a logistic distribution function used to construct the time-varying coefficients. If left empty, the scale parameters are drawn randomly. Default is NULL.

polynomial_coef

A p \times d \times K array of coefficients for the polynomials used to construct the time-varying coefficients. If left empty, the polynomial coefficients are drawn randomly. Default is NULL.

sd_error

Standard deviation of the error innovations. Default is 1.

Details

With both dynamic = TRUE and intercept = TRUE, the current implementation requires p \geq 3 to construct the lag and intercept columns correctly; smaller values do not give the stated model.

Apart from the first observation of each unit when dynamic = TRUE, the scalar dependent variable y_{it} is generated according to the time-varying panel data model

y_{it} = \gamma_i + \bold{\beta}^\prime_{i} (t/T) \bold{x}_{it} + u_{it}, \quad i = 1, \dots, N, \; t = 1, \dots, T,

where \gamma_i is an individual fixed effect and \bold{x}_{it} is a p \times 1 vector of explanatory variables. The p \times 1 coefficient vector \bold{\beta}_i (t/T) follows the group pattern

\bold{\beta}_i \left( \frac{t}{T} \right) = \sum_{k = 1}^K \bold{\alpha}_k \left( \frac{t}{T} \right) \bold{1} \{i \in G_k \},

with \cup_{k = 1}^K G_k = \{1, \dots, N\}, G_k \cap G_j = \emptyset, and \sup_{v \in [0,1]} \| \bold{\alpha}_k(v) - \bold{\alpha}_j(v) \| \neq 0 for any k \neq j, k,j = 1, \dots, K. The total number of groups K is determined by n_groups.

The individual fixed effects \gamma_i and non-constant, non-lagged predictors are drawn independently from N(0,1). The optional intercept is one, and the lagged outcome is constructed from the simulated responses.

With error_spec = "iid", the errors u_{it} are independent normal draws with standard deviation sd_error. With error_spec = "AR", they follow an AR(1) process with coefficient 0.5 and innovations of the same standard deviation.

If locations = NULL, the location parameters are drawn from \sim Unif[0.3, 0.9]. If scales = NULL, the scale parameters are drawn from \sim Unif[0.01, 0.09]. If polynomial_coef = NULL, the polynomial coefficients are drawn from Unif[-20, 20] and shifted so that the coefficients of each polynomial sum to 1. Before any dynamic rescaling, each coefficient function is \alpha_{k,l}(t/T) = 3 F(t/T, location_{k,l}, scale_{k,l}) + \sum_{j=1}^d a_{j,k,l} (t/T)^j, where F is the logistic distribution function. If dynamic = TRUE, the first coefficient function in each group is divided by its maximum absolute value plus 10^{-4}.

Value

A list holding

alpha

a T \times p \times K array of group-specific time-varying parameters.

beta

a T \times p \times N array of individual time-varying parameters.

groups

a vector indicating the group memberships (g_1, \dots, g_N), where g_i = k if i \in group k.

y

a vector of NT outcomes, ordered by unit and then time.

X

a matrix of explanatory variables, ordered by unit and then time.

data

a data.frame containing the outcome and explanatory variables in the same order.

Author(s)

Paul Haimerl

See Also

sim_DGP for simulating a static panel data set, fuse_time for jointly estimating the latent group structure and group-specific time-varying coefficients, and grouped_tv_plm for estimation given an observed group structure.

Examples

# Simulate a time-varying panel subject to a time trend and a group structure
set.seed(1)
sim <- sim_tv_DGP(N = 20, n_periods = 50, p = 1)
y <- sim$y
X <- sim$X