% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/build_temporal_rf.R
\name{build_temporal_rf}
\alias{build_temporal_rf}
\title{Build Temporal Random Forest Models Across Cross-Validation Folds}
\usage{
build_temporal_rf(partition_result, pseudoabsence_result, model_vars,
                  rf_params = list(), threshold_method = "tss",
                  output_dir = file.path(tempdir(), "RF_Models"),
                  create_plot = TRUE, plot_palette = "Dark 2",
                  overwrite = FALSE, time_cols = NULL, verbose = TRUE)
}
\arguments{
\item{partition_result}{List or character. Output from
\code{\link{spatiotemporal_partition}} or path to an \code{.rds}
file containing that output.}

\item{pseudoabsence_result}{List or character. Output from
\code{\link{generate_absences}} or path to an \code{.rds} file
containing that output.}

\item{model_vars}{Character vector. Names of predictor columns to include in
the Random Forest. All variables must be present as columns in both the
presence and pseudoabsence data.}

\item{rf_params}{Named list. Additional arguments passed to
\code{\link[randomForest]{randomForest}}, such as \code{ntree} (number of
trees, default 500), \code{mtry} (number of variables tried at each split,
default \code{floor(sqrt(length(model_vars)))}), and \code{nodesize}
(minimum node size, default 1 for classification). Default is an empty
list, which uses \pkg{randomForest} defaults.}

\item{threshold_method}{Character or numeric. Method used to convert
continuous predicted probabilities to binary suitability. Accepted values:
\itemize{
  \item \code{"prevalence"}: Sets threshold equal to the prevalence
    (proportion of presences) in the training data for that fold.
  \item \code{"tss"}: Selects the threshold that maximizes the True Skill
    Statistic (sensitivity + specificity - 1) on the training data.
    Default.
  \item A numeric value between 0 and 1 (e.g. \code{0.4}): Uses that
    value as a fixed threshold for all folds directly.
}}

\item{output_dir}{Character. Directory to write output files including saved
model objects and plots. Default is \code{file.path(tempdir(), "RF_Models")}.}

\item{create_plot}{Logical. If \code{TRUE}, generates a per-fold variable
importance plot, partial dependence curves for each predictor, and a
combined ROC curve summary. Default is \code{TRUE}.}

\item{plot_palette}{Character. Name of an HCL or RColorBrewer palette used
to color folds in diagnostic plots. Accepts any HCL palette name (see
\code{\link[grDevices]{hcl.pals}}) or, if \pkg{RColorBrewer} is installed,
any Brewer palette name. Default is \code{"Dark 2"}.}

\item{overwrite}{Logical. If \code{TRUE}, overwrites existing saved model
files. If \code{FALSE}, loads existing files when available. Default is
\code{FALSE}.}

\item{time_cols}{Character. Name of the column(s) containing year or time
step values in the occurrence data. Must match \code{time_cols} used in
\code{\link{spatiotemporal_partition}}. Default is \code{NULL}.}

\item{verbose}{Logical. If \code{TRUE} (default), prints progress
messages during processing. Includes per-fold training summaries and
file-saved messages.}
}
\value{
A list with class \code{"TemporalRF"} containing:
\itemize{
  \item \code{models}: Named list of fitted \code{randomForest} objects,
    one per fold.
  \item \code{thresholds}: Named numeric vector of probability thresholds
    used for binary classification, one per fold.
  \item \code{threshold_method}: Character string recording the thresholding
    method used.
  \item \code{model_vars}: Character vector of predictor names used.
  \item \code{variable_importance}: Named list of importance data frames,
    one per fold, with mean decrease in accuracy for each predictor.
  \item \code{fold_training_data}: Named list of training data frames used
    to fit each fold model, retained for downstream prediction.
  \item \code{fold_test_metrics}: Data frame of held-out test fold metrics
    per fold: \code{Threshold}, \code{AUC}, \code{TSS}, \code{Kappa},
    \code{Sensitivity}, and \code{Specificity}. Also written to
    \code{Fold_Test_Metrics.csv} in \code{output_dir}.
  \item \code{output_dir}: Path to the output directory.
  \item \code{model_type}: Character string \code{"rf"}, used by
    \code{\link{generate_spatiotemporal_predictions}}.
  \item \code{plots}: Named list of recorded plot objects when
    \code{create_plot = TRUE}. Plots can be replayed with
    \code{grDevices::replayPlot()}.
}
}
\description{
Modeling function that constructs Random Forest classification models for
each cross-validation fold using presence and pseudoabsence data. Each model
reserves one fold as testing data and uses the remaining folds as training
data. The user specifies predictors as a character vector.
Predicted probabilities of presence are extracted from the
out-of-bag or in-bag vote fractions and thresholded to produce binary
suitability classifications. Variable importance is recorded for each fold.
The returned object follows the same
structure as \code{\link{build_temporal_glm}}, \code{\link{build_temporal_gam}},
and \code{\link{build_temporal_hv}}, and is accepted directly by
\code{\link{generate_spatiotemporal_predictions}}.
}
\details{
Random Forests are fit using \code{\link[randomForest]{randomForest}} from
the \pkg{randomForest} package. The response is treated as a factor
(\code{0}/\code{1}) so the model runs in classification mode, which produces
class vote fractions used as predicted probabilities. Importance is computed
with \code{importance = TRUE} and \code{type = 1} (mean decrease in
accuracy).

Predicted probabilities are the vote fraction for class \code{1} from
\code{predict(..., type = "prob")[, "1"]}. These are used for threshold
selection and ROC curve construction.

Diagnostic plots include: a variable importance bar chart (mean decrease in
accuracy across folds), partial dependence curves for each predictor showing
the marginal effect of each variable while averaging over all others (with
rug marks for presences and pseudoabsences), and a combined ROC curve panel.

The returned object is recognized by
\code{\link{generate_spatiotemporal_predictions}}, which uses the
\code{model_type} field to use the correct prediction and evaluation
logic.
}
\examples{
data(tmr_partition, package = "TemporalModelR")

data(tmr_absences,  package = "TemporalModelR")

build_temporal_rf(
  partition_result     = tmr_partition,
  pseudoabsence_result = tmr_absences,
  model_vars           = c("elevation", "forest_cover", "prseas"),
  rf_params            = list(ntree = 100),
  threshold_method     = "tss",
  output_dir           = tempdir(),
  create_plot          = FALSE,
  time_cols            = c("year", "season"),
  verbose              = FALSE
)
}
\seealso{
Preprocessing: \code{\link{spatiotemporal_partition}},
  \code{\link{generate_absences}}

Modeling: \code{\link{build_temporal_glm}}, \code{\link{build_temporal_gam}},
  \code{\link{build_temporal_hv}},
  \code{\link{generate_spatiotemporal_predictions}}

External: \code{\link[randomForest]{randomForest}}
}
