% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/gridded.R
\name{ck_apply_grid}
\alias{ck_apply_grid}
\title{Apply a climatekit Index Function Over a SpatRaster}
\usage{
ck_apply_grid(x, fun, dates, ...)
}
\arguments{
\item{x}{A SpatRaster. Layers correspond one-to-one with \code{dates}.}

\item{fun}{A \verb{ck_*} function (or any function with the same
signature: numeric vector + Date vector + optional named
arguments, returning a data frame with \code{period} and \code{value}).}

\item{dates}{Date vector of length \code{terra::nlyr(x)}.}

\item{...}{Additional named arguments forwarded to \code{fun} (for
example \code{period = "annual"}, \code{ref_start}, \code{ref_end}).}
}
\value{
A SpatRaster with one layer per output period (layer names
are the period labels).
}
\description{
Compute a daily climatekit index function for every cell in a
SpatRaster \code{x} whose layers represent successive days, and return
the per-period results as a SpatRaster. The supplied function \code{fun}
must accept a numeric vector and a Date vector and return a data
frame with \code{period} and \code{value} columns (the standard climatekit
shape).
}
\details{
All cells must share the same \code{dates}. Cells that are entirely \code{NA}
are returned as \code{NA}. Run-time scales linearly with the number of
cells; for very large grids consider sub-setting first.
}
\examples{
\donttest{
  if (requireNamespace("terra", quietly = TRUE)) {
    dates <- seq(as.Date("2024-01-01"), as.Date("2024-12-31"), by = "day")
    n <- length(dates)
    # Tiny 2x2 SpatRaster of synthetic daily Tmax
    r <- terra::rast(nrows = 2, ncols = 2, nlyrs = n,
                     xmin = 0, xmax = 2, ymin = 0, ymax = 2)
    set.seed(1)
    for (i in seq_len(n)) {
      terra::values(r[[i]]) <- rnorm(4, 15, 5)
    }
    txx_r <- ck_apply_grid(r, ck_txx, dates = dates, period = "annual")
    terra::nlyr(txx_r)
  }
}
}
