Within / between (Mundlak) decomposition for longitudinal data
Source:R/within_between.R
within_between.RdFor each variable in vars, adds two new columns to data:
Usage
within_between(data, group, vars, suffix = c("_btw", "_wtn"), na.rm = TRUE)Arguments
- data
A data frame.
- group
Character name (or character vector of names) identifying the grouping column(s). With multiple names, grouping is by the interaction.
- vars
Character vector of numeric columns to decompose. Must all exist in
data.- suffix
Length-2 character vector giving the suffixes for the between- and within-group columns. Default
c("_btw", "_wtn").- na.rm
Logical; passed to
mean()when computing per-group means. DefaultTRUE.
Details
<var><suffix[1]>- the per-group mean ofvar(the between-group component, constant within each group),<var><suffix[2]>-var - <var><suffix[1]>(the within-group deviation, summing to zero within each group).
The decomposition is exact: data[[var]] == data[[btw]] + data[[wtn]].
Including both columns in a regression (~ x_btw + x_wtn) separates the
cross-group association from the within-group association without imposing
that they be the same coefficient (the random-effects assumption).
Typical use in the MOTIVATE cover-resurvey workflow:
plots <- within_between(plots, group = "plot_id", vars = "year")
fit <- tobs(~ year_btw + year_wtn + bym2(graph = adj), data = plots,
family = cover("beta"), y = plots$cover,
method = "nested_laplace")year_wtn then carries the within-plot temporal trend; year_btw absorbs
across-plot timing heterogeneity (older versus newer baseline plots).