% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fkruskal_test.R
\name{f_kruskal_test}
\alias{f_kruskal_test}
\title{Perform multiple Kruskal-Wallis tests with a user-friendly output file, do data inspection and Dunn's test (of 'rstatix') as post hoc.}
\usage{
f_kruskal_test(
  formula,
  data = NULL,
  plot = TRUE,
  alpha = 0.05,
  output_type = "default",
  save_as = NULL,
  save_in_wdir = FALSE,
  intro_text = TRUE,
  adjust = "bonferroni",
  close_generated_files = FALSE,
  open_generated_files = interactive(),
  ...
)
}
\arguments{
\item{formula}{A formula specifying the response and predictor variable (e.g., \code{response ~ predictor)}.
more response variables and predictors can be added using \code{-} or \code{+} (e.g., \code{response1 + response2 ~ predictor1 + predictor2)}. The function iterates through these combinations or response and predictors, because the Kruskal-Wallis test itself only allows one response and one predictor combination to be tested simultaneously.}

\item{data}{A \code{data.frame} containing the variables referenced in the formula.}

\item{plot}{Logical. If \code{TRUE}, generates plots (e.g., density plots and boxplots)
in the output files. Default is \code{TRUE}.}

\item{alpha}{Numeric. The significance level for the Kruskal-Wallis test and Dunn's
test. Default is  \code{0.05}.}

\item{output_type}{Character string specifying the output format. Default is \code{"default"}.
\itemize{
  \item \code{"default"}: Returns the object and lets R decide whether
    to print; auto-prints if unassigned, silent if assigned to a variable.
    Use \code{print(result)} or \code{plot(result)} to display the
    returned object.
  \item \code{"console"}: Forces immediate printing to the console
    regardless of object assignment.
  \item \code{"pdf"}, \code{"word"}, \code{"excel"}: Saves results to a
    file of the corresponding format. See \code{save_as},
    \code{save_in_wdir}, and \code{open_generated_files} for file
    path and opening behavior.
  \item \code{"rmd"}: Stores the raw markdown string inside the returned
    object for use in R Markdown documents.
}}

\item{save_as}{Character string specifying the output file path (without extension).
If a full path is provided, output is saved to that location.
If only a filename is given, the file is saved in \code{tempdir()}.
If only a directory is specified (providing an existing directory with trailing slash),
the file is named "dataname_Kruskal_Wallis_output" in that directory. If an extension is provided the output format specified with option "output_type" will be overruled.
Defaults to \code{file.path(tempdir(), "dataname_summary.pdf")}.}

\item{save_in_wdir}{Logical. If \code{TRUE}, saves the file in the working directory. Default is \code{FALSE}, this avoid unintended changes to the global environment. If \code{save_as} location is specified \code{save_in_wdir} is overwritten by \code{save_as}.}

\item{intro_text}{Logical. If \code{TRUE}, includes a section about Kruskal-Wallis test assumptions in the output document. Default is \code{TRUE}.}

\item{adjust}{Character string. Adjustment method for pairwise comparisons in Dunn's test. Options include \code{"holm", "hommel", "bonferroni", "hochberg", "bh", "by", "fdr"} or \code{"none"}. Default is \code{"bonferroni"}, if you don't want to adjust the p value (not recommended), use \code{adjust = "none"}.}

\item{close_generated_files}{Logical. Closes open Excel or Word (NOT pdf) files before writing, depending on the output format. Works on Windows (taskkill), macOS (pkill) and Linux (pkill/soffice). Default \code{FALSE}. \strong{WARNING:} Always save your work before using this option!!}

\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[stats]{kruskal.test}}.
The arguments \code{subset} and \code{na.action} are honored: when
supplied, they are applied via \code{\link[stats]{model.frame}} so
that the descriptive summary table, density plot, boxplot, Dunn's
post hoc test and the Kruskal-Wallis test itself all see the exact
same row set.}
}
\value{
An object of class 'f_kruskal_test' (a named list, one entry per
  response-predictor combination) containing:
  \describe{
    \item{kruskal.test}{The \code{htest} object from \code{kruskal.test()}.}
    \item{dunn_test}{Data frame of pairwise Dunn's test results from \code{rstatix::dunn_test()}.}
    \item{summary_table}{Descriptive statistics with compact letter display (Letters column).}
    \item{alpha}{The significance level used.}
    \item{DunnTest_adjust}{The p-value adjustment method used.}
    \item{distributions}{ggplot density plot (if \code{plot = TRUE}).}
    \item{Boxplot}{ggplot boxplot with CLD letters (if \code{plot = TRUE}).}
  }

Using the option \code{output_type}, it can also generate output in the form of: R Markdown code, 'Word', 'pdf', or 'Excel' files. Includes print and plot methods for 'f_kruskal_test' objects.
}
\description{
Performs the Kruskal-Wallis rank sum test to assess whether there are statistically significant differences in the distributions (mean ranks) of three or more independent groups. It provides detailed outputs, including plots, assumption checks, and post hoc analyses using Dunn's test. Results can be saved in various formats ('pdf', 'Word', 'Excel', or console only) with customizable output options.
}
\details{
This function offers a comprehensive workflow for non-parametric analysis using the Kruskal-Wallis test:
\itemize{
\item Assumption Checks: Optionally includes a summary of assumptions in the output.
\item Visualization: Generates density plots and boxplots to visualize group distributions.
\item Post hoc Analysis: Conducts Dunn's test with specified correction methods if significant differences are found.
}
-----------\cr

Output files are generated in the format specified by \code{output_type =} and saved to the working directory, options are \code{"pdf", "word"} or \code{"excel"}. If \code{output_type = "rmd"} is used it is advised to use it in a chunk with \{r, echo=FALSE, results='asis'\}

This function requires [Pandoc](https://github.com/jgm/pandoc/releases/tag) (version 1.12.3 or higher), a universal document converter.
\itemize{
\item \bold{Windows:} Install Pandoc and ensure the installation folder \cr (e.g., "C:/Users/your_username/AppData/Local/Pandoc") is added to your system PATH.
\item \bold{macOS:} If using Homebrew, Pandoc is typically installed in "/usr/local/bin". Alternatively, download the .pkg installer and verify that the binary's location is in your PATH.
\item \bold{Linux:} Install Pandoc through your distribution's package manager (commonly installed in "/usr/bin" or "/usr/local/bin") or manually, and ensure the directory containing Pandoc is in your PATH.

\item If Pandoc is not found, this function may not work as intended.
}
}
\section{Multiple Testing Across Response Variables}{

When several response variables are analysed in a single call
(e.g. \code{y1 + y2 + y3 ~ treatment}), each Kruskal-Wallis test is an
independent null-hypothesis test at level \code{alpha}. The post hoc
adjustment (e.g. \code{adjust = "bonferroni"}) only controls the
family-wise error rate \strong{within} one test (across pairwise Dunn
comparisons for that response). It does \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}.
}

\examples{
# Example usage:
data(iris)

# Perform Kruskal-Wallis test on Sepal.Length and Sepal.Width by Species
# with "holm" correction for posthoc dunn_test, without showing the output.
output <- f_kruskal_test(
               Sepal.Width + Sepal.Length ~ Species,
               data = iris,
               plot = FALSE,
               output_type = "word",
               adjust = "holm"
               )

# Save Kruskal-Wallis test and posthoc to Excel sheets: Sepal.Width and Sepal.Length.
f_kruskal_out <- f_kruskal_test(
                     Sepal.Width + Sepal.Length ~ Species,
                     data = iris,
                     plot = FALSE,
                     output_type = "excel",
                     adjust = "holm"
                     )

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