% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/createCovariates.R
\name{createCovariates}
\alias{createCovariates}
\title{Extract covariate values from spatial rasters and prepare rasters for spatial predictions}
\usage{
createCovariates(
  CTtable,
  directory,
  filenames,
  rasters,
  buffer_ct = 0,
  bilinear = FALSE,
  buffer_aoi = 1000,
  raster_template = NULL,
  resolution = NULL,
  append = TRUE,
  formats = ".tif",
  recursive = FALSE,
  download_elevation = FALSE,
  elevation_zoom = 10,
  terrain_measures = NULL,
  standardize_na = FALSE,
  scale_covariates = FALSE
)
}
\arguments{
\item{CTtable}{sf object as defined by the \code{sf} package. Essentially a camera trap data frame with spatial information.}

\item{directory}{character. The directory containing the covariate rasters.}

\item{filenames}{character (optionally named). A vector of file paths of covariate rasters. If it is named the covariates will be named according to the names. If unnamed the file names will be used as covariate names.}

\item{rasters}{SpatRaster object or list of SpatRaster objects. Direct input of rasters from the terra package instead of reading from disk.}

\item{buffer_ct}{numeric. A value (in meters) by which to buffer the point locations in \code{CTtable} for extraction of covariate values.}

\item{bilinear}{logical. If \code{TRUE}, extract covariate values with bilinear interpolation (nearest 4 raster cells). If \code{FALSE}, extract value at the cell the point falls in. Only relevant if \code{buffer_ct} is 0.}

\item{buffer_aoi}{numeric. A value (in meters) by which to buffer the overall camera trapping grid to ensure that prediction rasters are larger than the camera trapping grid.}

\item{raster_template}{SpatRaster. A SpatRaster (as defined in the \code{terra} package) to use as template for the creation of prediction rasters.}

\item{resolution}{numeric. Spatial resolution of prediction rasters in the units of the coordinate reference system. Ignored if \code{raster_template} is provided.}

\item{append}{logical. If \code{TRUE}, add the extracted covariates to the existing \code{CTtable}. If \code{FALSE}, return only the extracted covariate values without the existing \code{CTtable}.}

\item{formats}{character. Possible file formats for raster data (must include the dot). Defaults to \code{.tif} files.}

\item{recursive}{logical. If \code{TRUE}, search for raster files recursively in subdirectories when a directory is provided. Defaults to \code{FALSE}.}

\item{download_elevation}{logical. If \code{TRUE}, download elevation data from AWS. Defaults to \code{FALSE}.}

\item{elevation_zoom}{numeric. Zoom level for elevation data download (6-12). Higher values provide more detail but longer download times. Zoom 12 corresponds to ~20m pixel resolution, 11 to ~40m, 10 to ~80m, and so on (resolution halves with each decrease in zoom level). Defaults to 9.}

\item{terrain_measures}{character. Vector of terrain metrics to calculate from elevation data. Options include "slope" (slope in degrees), "aspect" (compass direction in degrees), "TRI" (Terrain Ruggedness Index, measuring elevation difference between adjacent cells), "TPI" (Topographic Position Index, comparing cell elevation to mean of surrounding cells), and "roughness" (difference between max and min of surrounding cells). Defaults to NULL (no terrain metrics).}

\item{standardize_na}{logical. Logical. If \code{TRUE}, ensures all layers in the prediction raster have identical NA patterns by setting a cell to NA in all bands if it's NA in any band. This creates consistency for spatial predictions across covariates but may lose data in covariates.}

\item{scale_covariates}{logical. If \code{TRUE}, scale numeric covariates and return both original and scaled versions of data and prediction rasters. Scaling is performed using R's \code{scale} function. Defaults to \code{FALSE}.}
}
\value{
\describe{
When \code{scale_covariates = FALSE}, a list containing three elements:
  \item{CTtable}{An \code{sf} object representing the camera trap data frame with extracted covariate values.}
  \item{predictionRaster}{A \code{SpatRaster} object containing covariate raster layers}
  \item{originalRaster}{A list of the original input rasters}

When \code{scale_covariates = TRUE}, a list containing six elements:
  \item{CTtable}{The original \code{sf} object with unscaled covariate values}
  \item{CTtable_scaled}{The \code{sf} object with scaled numeric covariate values}
  \item{predictionRaster}{The original unscaled prediction raster}
  \item{predictionRaster_scaled}{The prediction raster with scaled numeric layers}
  \item{originalRaster}{A list of the original input rasters}
  \item{scaling_params}{A list containing center and scale information of numeric covariates}
}
}
\description{
This function extracts covariate values from spatial raster data 
 (e.g. for use in modelling) and prepares these covariates for use in 
 spatial predictions. 
 
 It accepts a camera trap table containing spatial information, 
 along with either a directory containing covariate raster files, a character 
 vector specifying the file paths of these covariate rasters, or direct
 SpatRaster objects from the terra package.
 
 Additionally, users can provide parameters to control how covariates are
 extracted, and how they are aggregated to prediction rasters.
 
 The function can also download elevation data and calculate terrain metrics
 if requested.
 
 The function generates prediction rasters based on a provided template or 
 creates one automatically if no template is provided.
 
 The function returns a list containing the camera trap dataset with 
 extracted covariate values (e.g for use in occupancy modelling), and 
 prediction rasters ready for spatial modeling.
}
\details{
The input camera trap table must be an \code{\link[sf]{sf}} object (a data 
frame with a geometry column specifying the spatial information). For details 
on how to convert an exising camera trap table to sf, see the examples below.
The input rasters can be in different coordinate systems. During covariate 
extraction the CTtable is projected to each raster's coordinate system 
individually. For the prediction raster all input rasters are either 
resampled or reprojected to a consistent coordinate system.

When \code{recursive = TRUE} and a directory is provided, the function will search
for raster files in all subdirectories. In this case, the subdirectory names are
used as covariate names, and only one raster file per subdirectory is allowed.

When \code{download_elevation = TRUE}, the function will download elevation data
from AWS using the \code{elevatr} package. The \code{elevation_zoom}
parameter controls the level of detail, with values between 6 and 12.
Higher zoom levels provide finer resolution but require longer download times and
may consume significant memory. Approximate resolutions: zoom 12 = ~20m, 
11 = ~40m, 10 = ~80m, etc.

If \code{terrain_measures} is specified, the function calculates the requested 
terrain metrics from the elevation data using \code{terra::terrain()} with the 
default 3x3 neighborhood. Available terrain metrics include "slope", "aspect", 
"TRI" (Terrain Ruggedness Index), "TPI" (Topographic Position Index), and 
"roughness".

When using \code{scale_covariates = TRUE}, the function returns both original and
scaled versions of the data and prediction rasters. #' The function uses R's 
\code{scale()} function to perform centering and scaling, and
includes the scaling parameters in the returned metadata.

\subsection{Warning about Categorical Covariates}{
This function does not explicitly handle categorical rasters. All raster values are
treated as numeric, which can be problematic when scaling is applied. The function
attempts to identify "likely categorical" variables (numeric variables with few unique
integer values) and will provide warnings, but it cannot automatically handle them
correctly for scaling.

When using scaled covariates with categorical variables in models:
\itemize{
  \item Use \code{CTtable_scaled} for numeric predictors
  \item Use \code{CTtable} (original) for categorical predictors
  \item Similarly, use \code{predictionRaster_scaled} for numeric predictors in spatial predictions
  \item Use \code{predictionRaster} for categorical predictors in spatial predictions
}

Future versions may implement proper categorical raster handling with RAT (Raster
Attribute Table) support.
}
}
\examples{

\dontrun{
# load camera trap table
data(camtraps)

# create sf object
camtraps_sf <- st_as_sf(camtraps, 
                        coords = c("utm_x", "utm_y"), 
                        crs = 32650)

# extract covariates (with 100m buffer around cameras)
# doesn't run because 'directory' is only a placeholder

covariates <- createCovariates(camtraps_sf, 
"path/to/covariate_rasters", 
buffer_ct = 100, 
buffer_aoi = 1000,
resolution = 100)


# extract covariates with elevation data (this code runs)

covariates_elev <- createCovariates(camtraps_sf,
buffer_ct = 100,
buffer_aoi = 1000,
resolution = 100,
download_elevation = TRUE,
elevation_zoom = 11,
terrain_measures = c("slope", "aspect", "TRI"))

# Note that if local rasters are available they can be extracted alongside
# elevation data in a single function call

# camera trap table with extracted covariate values
camtraps_sf_cov <- covariates_elev$CTtable

# covariate raster layer
r_cov <- covariates_elev$predictionRaster
plot(r_cov)

# Use SpatRaster objects directly as input
r1 <- rast("elevation.tif")
r2 <- rast("landcover.tif")
raster_list <- list(elevation = r1, landcover = r2)

covariates_direct <- createCovariates(camtraps_sf,
                                      rasters = raster_list,
                                      buffer_ct = 100,
                                      resolution = 100)

# Scale numeric covariates for modeling
covariates_scaled <- createCovariates(camtraps_sf,
                                      rasters = raster_list,
                                      buffer_ct = 100,
                                      resolution = 100,
                                      scale_covariates = TRUE)

# Use scaled data with categorical variables
# Mix and match from original and scaled outputs for tabular data
model_data <- covariates_scaled$CTtable_scaled  # Use scaled numeric covariates
model_data$landcover <- covariates_direct$CTtable$landcover  # Use original categorical covariate

# Mix and match for prediction rasters
# Create combined prediction raster (scaled numeric variables & original categorical variables)
# Extract scaled elevation layer
elev_scaled <- covariates_scaled$predictionRaster_scaled$elevation

# Extract original landcover layer (categorical)
landcover_orig <- covariates_direct$predictionRaster$landcover

# Combine into a new SpatRaster for predictions
prediction_raster <- c(elev_scaled, landcover_orig)
names(prediction_raster) <- c("elevation", "landcover")

# Use this combined raster for spatial predictions
plot(prediction_raster)
}

}
