% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/flmer.R
\name{f_lmer}
\alias{f_lmer}
\title{Fit a linear mixed model with \code{lme4::lmer()} including assumption checks, diagnostics, R-squared and post hoc tests.}
\usage{
f_lmer(
  formula,
  data = NULL,
  REML = TRUE,
  ddf = "Satterthwaite",
  alpha = 0.05,
  adjust = "sidak",
  norm_plots = TRUE,
  post_hoc = TRUE,
  intro_text = TRUE,
  output_type = "default",
  save_as = NULL,
  save_in_wdir = FALSE,
  close_generated_files = FALSE,
  open_generated_files = interactive(),
  ...
)
}
\arguments{
\item{formula}{A two-sided formula passed to \code{lme4::lmer()}, e.g.
  \code{y ~ treatment + time + (1 | subject)} or
  \code{y ~ treatment * time + (1 + time | subject)}. The right-hand
  side must contain at least one random-effects term in the
  \code{(varying | grouping)} syntax. See \emph{Details} for a guide to
  reading the random-effects syntax in study-design terms.

  More than one response variable can be supplied on the left-hand side
  using \code{+} (e.g. \code{y1 + y2 ~ treatment + (1 | subject)}).
  A separate model is then fit for each response, sharing the same
  right-hand side, and a multiple-testing warning is added to the
  report. See the \emph{Multiple Testing Across Response Variables}
  section.}

\item{data}{A data frame containing the variables in the model.}

\item{REML}{Logical. If \code{TRUE} (default), the model is fit with
restricted maximum likelihood, which gives less biased variance
component estimates and is the appropriate choice for inference on
fixed effects with Kenward-Roger or Satterthwaite degrees of freedom.
Set to \code{FALSE} only when comparing nested models that differ in
their fixed-effects structure.}

\item{ddf}{Character. Method for computing denominator degrees of
freedom for fixed-effects p-values. One of:
\describe{
  \item{\code{"Satterthwaite"}}{(default) Fast and accurate for most
    designs. Provided by \code{lmerTest}.}
  \item{\code{"Kenward-Roger"}}{Considered the gold standard, especially
    for small samples and unbalanced designs. Slower, and requires the
    \code{pbkrtest} package.}
  \item{\code{"lme4"}}{No p-values; only t-statistics are reported.
    Equivalent to a plain \code{lme4::lmer()} summary.}
}}

\item{alpha}{Numeric. Significance level for the fixed-effects table and
the post hoc tests. Default is \code{0.05}.}

\item{adjust}{Character. Method used to adjust p-values for multiple
pairwise comparisons in the post hoc step (passed to
\code{emmeans::emmeans()}). One of \code{"sidak"} (default),
\code{"tukey"}, \code{"bonferroni"}, \code{"fdr"}, \code{"none"}.}

\item{norm_plots}{Logical. If \code{TRUE} (default), diagnostic plots
(residuals vs fitted, Q-Q of level-1 residuals, Q-Q of random-effect
BLUPs, scale-location) are included in the output.}

\item{post_hoc}{Logical. If \code{TRUE} (default), runs
\code{emmeans::emmeans()} pairwise comparisons \strong{only when}
the linear mixed model finds a significant fixed-effect term
(ANOVA p-value below \code{alpha}). The post hoc is performed on
each significant factor fixed-effect term separately. Numeric
covariates are skipped because their slope is already reported in
the fixed-effects coefficient table; pairwise contrasts are not
meaningful for a continuous predictor. If no fixed-effect term is
significant, no post hoc is run.}

\item{intro_text}{Logical. If \code{TRUE} (default), prepends an
explanation of LMM assumptions and the random-effects syntax linked
to study design.}

\item{output_type}{Character. Output format. One of:
\itemize{
  \item \code{"default"}: returns the \code{f_lmer} object; auto-prints
    if unassigned.
  \item \code{"console"}: forces immediate printing.
  \item \code{"pdf"}, \code{"word"}, \code{"excel"}: writes a file.
  \item \code{"rmd"}: stores the raw markdown string in the returned
    object for embedding in an R Markdown chunk with
    \code{\{r, echo=FALSE, results='asis'\}}.
}}

\item{save_as}{Character. Output file path. See \code{\link{f_aov}}
for the resolution rules; default is
\code{file.path(tempdir(), "<dataname>_lmer_output.<ext>")}.}

\item{save_in_wdir}{Logical. If \code{TRUE}, save in the working
directory instead of \code{tempdir()}. Default \code{FALSE}.}

\item{close_generated_files}{Logical. Closes any open Word or Excel
files before writing. Cross-platform (Windows taskkill, macOS / Linux
pkill). Default \code{FALSE}. \strong{WARNING:} save your work first.}

\item{open_generated_files}{Logical. Whether to open the generated output
files after creation. Defaults to \code{TRUE} in an interactive R session
and \code{FALSE} otherwise (e.g. in scripts or automated pipelines).
Set to \code{TRUE} or \code{FALSE} to override this behaviour explicitly.}

\item{...}{Additional arguments forwarded to \code{\link[lmerTest]{lmer}}.
The arguments \code{subset}, \code{na.action}, and \code{weights}
are handled specially: when supplied, they are applied via
\code{\link[stats]{model.frame}} \strong{once} before the
per-response loop, so every response in a multi-response call is
fitted on the identical row set. Other \code{lmer()} arguments
(e.g. \code{control = lmerControl(...)}, \code{contrasts},
\code{offset}) are forwarded unchanged on every fit.}
}
\value{
An object of class \code{f_lmer}: a named list containing the
  fitted \code{lmerModLmerTest} model, the ANOVA-style fixed-effects
  table, the variance components and ICC, the R\eqn{^2} values, the
  observed descriptives table (raw-data n, mean, sd, se, min, Q1,
  median, Q3, max grouped by the categorical fixed-effect predictors),
  post hoc results (if any), diagnostic plots, and convergence
  diagnostics. When more than one response variable is supplied on the
  left-hand side, these elements are nested one level deep under each
  response name, e.g. \code{out$y1$fixed_effects},
  \code{out$y2$fixed_effects}. When \code{output_type = "rmd"} the
  markdown string is stored in \code{$rmd}.
}
\description{
Fits a linear mixed-effects model using \code{lme4::lmer()} (with p-values
from \code{lmerTest}) and produces a fully-formatted report containing
the fixed-effects table, random-effects variance components, model-fit
indices (AIC, BIC, logLik, marginal & conditional R\eqn{^2}), residual and
BLUP diagnostics, convergence / singular-fit warnings, and post hoc
comparisons (\code{emmeans}) on factor fixed effects. Results can be
returned to the console or written to 'pdf', 'Word' or 'Excel'.
}
\details{
\strong{What is a linear mixed model?}\cr
A linear mixed model (LMM) extends ordinary regression / ANOVA by
allowing two kinds of effects:
\itemize{
  \item \strong{Fixed effects} - factors you actively manipulated or
    whose specific levels you care about (treatment, dose, time,
    genotype). Reported as estimates with confidence intervals.
  \item \strong{Random effects} - grouping structure that creates
    non-independence in your data but whose levels are a random sample
    from a larger population (subjects measured repeatedly, plots
    within fields, observers, batches). Reported as variance
    components.
}
Use an LMM whenever observations share something that makes them more
alike than two random observations from the dataset. Ignoring such
grouping (running a plain \code{aov} or \code{lm}) is
\strong{pseudoreplication}, i.e. treating non-independent observations
as if they were independent: standard errors shrink, p-values shrink,
false positives explode.

\strong{Vocabulary.}\cr
Before going further, a few terms used throughout the report:
\itemize{
  \item \strong{Subject} - the experimental unit that is measured
    repeatedly (a person, animal, pot and plot, cell line); in
    \code{lme4} syntax it is the grouping factor on the right of
    the \code{|}, e.g. \code{(1 | subject)}.
  \item \strong{Within-subject factor} - a predictor whose levels
    vary within the same subject (time in a longitudinal study,
    treatment in a cross-over study).
  \item \strong{Between-subject factor} - a predictor whose levels
    vary across subjects but are constant within a subject (sex,
    genotype, treatment arm in a parallel-groups trial). Both
    within- and between-subject factors are \strong{fixed} effects.
  \item \strong{BLUP} - \emph{Best Linear Unbiased Predictor}. The
    model's estimate of the random-effect value for each subject
    (e.g. how much a particular subject deviates from the population
    intercept). BLUPs are checked for normality just like residuals.
  \item \strong{ICC} - \emph{intraclass correlation coefficient}.
    The share of total variance attributable to between-group
    differences. ICC = 0 means the grouping factor is irrelevant;
    ICC = 1 means observations within a group are identical.
  \item \strong{REML} - \emph{restricted maximum likelihood}. The
    default fitting method for variance components; gives less biased
    estimates than ordinary maximum likelihood.
  \item \strong{Satterthwaite / Kenward-Roger} - methods to approximate
    the denominator degrees of freedom for fixed-effect p-values,
    since there is no exact df in an LMM.
}

\strong{Reading the \code{(1 | group)} syntax.}\cr
Every random-effects term has the form \code{( <varying> | <group> )}.
The bar reads as "varies by". The grouping factor on the right is what
creates the non-independence. The left side is what is allowed to differ
between groups. Common patterns:
\itemize{
  \item \code{(1 | subject)} - random intercept per subject (each
    subject has its own baseline). Repeated measures, longitudinal data.
  \item \code{(1 | field)} - randomised block design or multi-site
    trial; one intercept per block.
  \item \code{(1 | field/plot)} - \code{plot} nested in \code{field};
    equivalent to \code{(1|field) + (1|field:plot)}. Split-plot or
    hierarchical sampling.
  \item \code{(1 + time | subject)} - random intercept and random slope
    of \code{time} per subject. Subjects differ both in baseline and
    in how fast they change. Growth curves.
  \item \code{(1 | subject) + (1 | observer)} - crossed random
    effects: every observer can rate every subject. Inter-rater designs.
}
\strong{Rule of thumb:} if you can answer "if I duplicated this
experiment, would I draw new levels of this factor?" with \emph{yes},
it belongs on the right of a \code{|}. If you would re-use the exact
same levels (e.g. control vs treated) it is a fixed effect.

\strong{When to use a linear mixed model.}\cr
The most common reason is a \strong{repeated-measures design}, in
which the same experimental units are measured on more than one
occasion or under more than one treatment. Compared with a
between-groups design analysed by plain ANOVA this gives two real
advantages: fewer experimental units are needed (each subject acts
as its own control, removing between-subject variation from the
comparison) and individual differences cannot bias the treatment
groups (in a cross-over design every subject receives every
treatment). Two canonical examples:
\itemize{
  \item \strong{Longitudinal study} - same subjects measured at
    several time points: \code{y ~ time + (1 | subject)}. If
    subjects also differ in how fast they change, add a random
    slope: \code{y ~ time + (1 + time | subject)}.
  \item \strong{Cross-over design} - every subject receives every
    treatment in sequence: \code{y ~ treatment + (1 | subject)}. If
    carry-over between periods is a concern, add \code{period} as
    a fixed effect.
}
LMMs also apply to non-repeated structures that still create
non-independence: randomised block designs, split-plot trials,
multi-site studies, inter-rater designs.

\strong{Assumptions of a linear mixed model:}
\enumerate{
  \item Linearity in the parameters of the fixed-effects part.
  \item Independence of observations \emph{conditional on} the random
    effects. If structure remains (e.g. temporal autocorrelation), more
    random effects or a correlation structure are needed.
  \item Normality of level-1 residuals (Q-Q plot of \code{residuals(m)}).
  \item Normality of the random-effect BLUPs
    (Q-Q plot of \code{ranef(m)}). \strong{This is the assumption most
    users forget.}
  \item Homoscedasticity: residual variance roughly constant across
    fitted values and across grouping levels.
  \item At least \code{~5} levels of each grouping factor; with
    \code{3-4} levels it is usually better to treat the factor as
    fixed.
}
If Levene's test or the Shapiro-Wilk tests on residuals or BLUPs
indicate a violation, the report adds a \emph{Recommendations for
Heteroscedasticity and/or non-normal residuals} section after the
diagnostics with concrete next steps (generalised mixed model,
transformation).

\strong{Convergence and singular fits.}\cr
\code{f_lmer} surfaces \code{lme4} convergence warnings and the
"boundary (singular) fit" message prominently in the output. A singular
fit usually means the random-effects structure is too complex for the
data (often a random slope with too few levels) - simplify the model
before interpreting results.

This function requires Pandoc (>= 1.12.3) for \code{pdf}, \code{word}
and \code{rmd} output. See \code{\link{f_aov}} for installation notes.
}
\section{Multiple Testing Across Response Variables}{

When several response variables are analysed in a single call
(e.g. \code{y1 + y2 + y3 ~ treatment + (1 | subject)}), each linear
mixed model is an independent null-hypothesis test at level
\code{alpha}. The post hoc adjustments (\code{adjust = "sidak"},
\code{"tukey"}, etc.) only control the family-wise error rate
\strong{within} one model (across pairwise contrasts for that
response). They do \strong{not} protect against the inflation of
Type I error \strong{across} the set of responses.

\strong{Practical implication:} With \eqn{k} independent response
variables all tested at \eqn{\alpha = 0.05}, the probability of
obtaining at least one false positive is
\eqn{1 - (1 - 0.05)^k}, which reaches ~40\% for \eqn{k = 10}.

\strong{When this matters:} The risk is highest in exploratory studies
where many responses are screened simultaneously without a clear
a priori hypothesis for each one. It is less of a concern when each
response is a pre-specified primary outcome with its own biological
rationale.

\strong{Possible remedies:}
\itemize{
  \item \strong{Bonferroni correction across responses:} use
    \code{alpha = 0.05 / k} where \code{k} is the number of response
    variables. Conservative but simple.
  \item \strong{False Discovery Rate (FDR):} apply
    \code{p.adjust(p_values, method = "fdr")} to the vector of
    per-response fixed-effect p-values after the fact.
  \item \strong{Multivariate model:} if the responses are correlated
    and you want a single omnibus test, fit a joint multivariate
    mixed model (e.g. \code{MCMCglmm}, \code{brms}) before
    interpreting individual responses.
  \item \strong{Pre-registration:} declare primary vs. exploratory
    responses before data collection to justify differential
    correction thresholds.
}
}

\examples{
# sleepstudy: reaction time vs days of sleep deprivation,
# repeated measures within Subject (ships with lme4).
data(sleepstudy, package = "lme4")

# 1) Random intercept per subject - the simplest mixed model.
#    Each subject has its own baseline reaction time; the fixed
#    effect of Days is the average slope across subjects.
#    With output_type = "default" (the default), the result auto-
#    prints if not assigned, so no print() call is needed.
f_lmer_out <- f_lmer(Reaction ~ Days + (1 | Subject),
                     data = sleepstudy)

# Re-print the stored result and show the diagnostic plots.
print(f_lmer_out)
plot(f_lmer_out)

# 2) Random intercept AND random slope of Days per subject,
#    fitted with Kenward-Roger denominator df, saved to MS Word.
f_lmer(Reaction ~ Days + (1 + Days | Subject),
       data = sleepstudy,
       ddf  = "Kenward-Roger",
       output_type = "word"
       )

# 3) A factor fixed effect triggers a post hoc test.
#    Bin Days into three sleep-deprivation phases so that the
#    fixed effect is categorical and emmeans pairwise comparisons
#    with a compact letter display are produced automatically.
sleepstudy$Phase <- cut(sleepstudy$Days,
                        breaks = c(-Inf, 2, 6, Inf),
                        labels = c("early", "mid", "late"))
f_lmer(Reaction ~ Phase + (1 | Subject),
       data = sleepstudy,
       adjust = "tukey")

# 4) A minimal report: suppress the intro text and the diagnostic
#    plots, and save it directly to MS Word. Useful when embedding
#    many models in one document or when you only need the tables.
f_lmer(Reaction ~ Days + (1 | Subject),
       data = sleepstudy,
       intro_text = FALSE,
       norm_plots = FALSE,
       output_type = "word"
       )

# 5) Get the raw markdown back for embedding in an R Markdown
#    document. Use it inside a chunk with results = 'asis'.
f_lmer_rmd_out <- f_lmer(Reaction ~ Days + (1 | Subject),
                         data = sleepstudy,
                         output_type = "rmd")
cat(f_lmer_rmd_out$rmd)

# 6) Two response variables analysed in one call. A separate model
#    is fit for each, sharing the same right-hand side. The results
#    are nested under each response name.
sleepstudy$Reaction2 <- sleepstudy$Reaction + rnorm(nrow(sleepstudy), 0, 5)
multi_out <- f_lmer(Reaction + Reaction2 ~ Days + (1 | Subject),
                    data = sleepstudy,
                    intro_text = FALSE,
                    norm_plots = FALSE)
multi_out$Reaction$fixed_effects
multi_out$Reaction2$fixed_effects

}
\author{
Sander H. van Delden  \email{plantmind@proton.me} \cr
}
