% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fboxcox.R
\name{f_boxcox}
\alias{f_boxcox}
\title{f_boxcox: A User-Friendly Box-Cox Transformation}
\usage{
f_boxcox(
  data = data,
  digits = 3,
  range = c(-2, 2),
  plots = NULL,
  transform.data = TRUE,
  eps = 1/50,
  xlab = expression(lambda),
  ylab = "log-Likelihood",
  alpha = 0.05,
  open_generated_files = interactive(),
  close_generated_files = FALSE,
  output_type = "default",
  save_as = NULL,
  save_in_wdir = FALSE,
  ...
)
}
\arguments{
\item{data}{A numeric vector or a data frame with a single numeric column. The data to be transformed.}

\item{digits}{Numeric. Determines the accuracy of the estimate for lambda. Higher values increase computation time. Defaults to \code{3}.}

\item{range}{A numeric vector of length 2 defining the search interval for lambda. Defaults to \code{c(-2, 2)}.}

\item{plots}{Logical. If \code{TRUE}, plots log-likelihood of the Box-Cox transformation, Histograms and Q-Q plots of the original and transformed data. Default is \code{FALSE}.}

\item{transform.data}{Logical. If \code{TRUE}, returns the transformed data. Default is \code{TRUE}.}

\item{eps}{A small positive value used to determine when to switch from the power transformation to the log transformation for numerical stability. Default is \code{1/50}.}

\item{xlab}{Character string. Label for the x-axis in plots. Default is an expression object representing \eqn{\lambda}.}

\item{ylab}{Character string. Label for the y-axis in plots. Default is "log-Likelihood".}

\item{alpha}{Numeric. Significance level for the Shapiro-Wilk test of normality. Default is \code{0.05}.}

\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{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{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 "data_name_aov_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(), "data_name_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{...}{Additional arguments passed to plotting functions.}
}
\value{
An object of class 'f_boxcox' containing, among others, results from the boxcox transformation, lambda, the input data, transformed data, Shapiro-Wilk test on original and transformed data. Using the option "output_type", it can also generate output in the form of: R Markdown code, 'Word', or 'pdf' files. Includes print and plot methods for 'f_boxcox' objects.
}
\description{
Performs a Box-Cox transformation on a dataset to stabilize variance and make the data more normally distributed. It also provides diagnostic plots and tests for normality. The transformation is based on code of MASS/R/boxcox.R. The function prints \eqn{\lambda} to the console and returns (output) the transformed data set.
}
\details{
The function uses the following formula for transformation:
\deqn{
 y(\lambda) =
   \begin{cases}
 \frac{y^\lambda - 1}{\lambda}, & \lambda \neq 0 \\  \log(y), & \lambda = 0
 \end{cases}
}

where (\eqn{y}) is the data being transformed, and (\eqn{\lambda}) the transformation parameter, which is estimated from the data using maximum likelihood. The function computes the Box-Cox transformation for a range of \eqn{\lambda} values and identifies the \eqn{\lambda} that maximizes the log-likelihood function. The beauty of this transformation is that, it checks suitability of many of the common transformations in one run. Examples of most common transformations and their \eqn{\lambda} value is given below:
\renewcommand{\arraystretch}{3} % Adjusts row height (default is 1)
\tabular{cc}{
  \strong{\eqn{\lambda}-Value} \tab \strong{Transformation} \cr
  \strong{-----------------------}\tab\strong{-----------------------}\cr
  -2          \tab \eqn{\frac{1}{x^2}}          \cr
  -1          \tab \eqn{\frac{1}{x}  }          \cr
  -0.5        \tab \eqn{\frac{1}{\sqrt{x}}}     \cr
  0           \tab \eqn{log(x)}                 \cr
  0.5         \tab \eqn{\sqrt{x}}               \cr
  1           \tab \eqn{x}                      \cr
  2           \tab \eqn{x^2}                    \cr
  \strong{-----------------------}\tab\strong{-----------------------}\cr
}

If the estimated transformation parameter closely aligns with one of the values listed in the previous table, it is generally advisable to select the table value rather than the precise estimated value. This approach simplifies interpretation and practical application.

The function provides diagnostic plots: a plot of log-likelihood against \eqn{\lambda} values and a Q-Q plot of the transformed data.It also performs a Shapiro-Wilk test for normality on the transformed data if the sample size is less than or equal to 5000.

\strong{Note}: For sample sizes greater than 5000, Shapiro-Wilk test results are not provided due to limitations in its applicability.

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.
}
}
\examples{
# Create non-normal data in a data.frame or vector.
df   <- data.frame(values = rlnorm(100, meanlog = 0, sdlog = 1))

# Store the transformation in object "bc".
bc <- f_boxcox(df$values)

# Print lambda and Shaprio.
print(bc)

# Plot the QQ plots, Histograms and Lambda Log-Likelihood estimation.
plot(bc)

# Or Directly use the transformed data from the f_boxcox object.
df$values_transformed <- f_boxcox(df$values)$transformed_data
print(df$values_transformed)

}
\references{
The core of calculating \eqn{\lambda} and the plotting was taken from: \cr
file MASS/R/boxcox.R copyright (C) 1994-2004 W. N. Venables and B. D. Ripley
\itemize{
\item \url{https://r-coder.com/box-cox-transformation-r/}
\item \url{https://CRAN.R-project.org/package=MASS}
}
Some code to present the result was taken and modified from file: \cr
rcompanion/R/transformTukey.r. (Developed by Salvatore Mangiafico)
\itemize{
\item \url{https://rcompanion.org/handbook/I_12.html}
}
The explanation on BoxCox transformation provided here was provided by r-coder:
\itemize{
\item  \url{https://r-coder.com/box-cox-transformation-r/}
}
}
\seealso{
\href{https://CRAN.R-project.org/package=MASS}{\code{boxcox}}
}
\author{
\itemize{
\item Sander H. van Delden  \email{plantmind@proton.me}
\item Salvatore Mangiafico, \email{mangiafico@njaes.rutgers.edu}
\item W. N. Venables and B. D. Ripley
}
}
