% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/aggregate.R
\name{aggregate.stars}
\alias{aggregate.stars}
\alias{aggregate}
\title{spatially or temporally aggregate stars object}
\usage{
\method{aggregate}{stars}(
  x,
  by,
  FUN,
  ...,
  drop = FALSE,
  join = st_intersects,
  as_points = any(st_dimension(by) == 2, na.rm = TRUE),
  rightmost.closed = FALSE,
  left.open = FALSE,
  exact = FALSE,
  weights = NULL,
  transform = NULL
)
}
\arguments{
\item{x}{object of class \code{stars} with information to be aggregated}

\item{by}{object of class \code{sf} or \code{sfc} for spatial aggregation, for temporal aggregation a vector with time values (\code{Date}, \code{POSIXct}, or \code{CFTime}) that is interpreted as a sequence of left-closed, right-open time intervals or a string like "months", "5 days" or the like (see \link{cut.POSIXt}), or a function that cuts time into intervals; if by is an object of class \code{stars}, it is converted to sfc by \code{st_as_sfc(by, as_points = FALSE)} thus ignoring its time component. Note: each pixel is assigned to only a single group (in the order the groups occur) so non-overlapping spatial features and temporal windows are recommended.}

\item{FUN}{aggregation function, such as \code{mean}}

\item{...}{arguments passed on to \code{FUN}, such as \code{na.rm=TRUE}}

\item{drop}{logical; ignored}

\item{join}{function; function used to find matches of \code{x} to \code{by}}

\item{as_points}{see \link[stars]{st_as_sf}: shall raster pixels be taken as points, or small square polygons?}

\item{rightmost.closed}{see \link{findInterval}}

\item{left.open}{logical; used for time intervals, see \link{findInterval} and \link{cut.POSIXt}}

\item{exact}{logical; if \code{TRUE}, use \link[exactextractr]{coverage_fraction} to compute exact overlap fractions of polygons with raster cells}

\item{weights}{single-layer \code{SpatRaster} or \code{stars} object on the same grid as \code{x} with secondary per-cell weights, e.g. population or cropland area. Only used when \code{exact = TRUE}, and cells with \code{NA} weight are treated as zero weight. Not supported for \code{stars_proxy} objects}

\item{transform}{function or one-sided formula, evaluated by \code{rlang::as_function}, applied to cell values before aggregation; e.g. \code{~ .x^2} or \code{~ pmax(0, .x - 10) - pmax(0, .x - 30)}. Units on \code{x} are dropped when set. Note: any transform that derives parameters from the values it is given is applied separately to each attribute (and to each chunk for \code{stars_proxy} objects), so its results may not be comparable across attributes or chunks, e.g. \code{splines::bs(.x)} places knots at quantiles of its input, so fix such parameters explicitly, as in \code{splines::bs(.x, knots = ..., Boundary.knots = ...)}}
}
\description{
spatially or temporally aggregate stars object, returning a data cube with lower spatial or temporal resolution
}
\examples{
# aggregate time dimension in format Date
tif = system.file("tif/L7_ETMs.tif", package = "stars")
t1 = as.Date("2018-07-31")
x = read_stars(c(tif, tif, tif, tif), along = list(time = c(t1, t1+1, t1+2, t1+3)))[,1:30,1:30]
st_get_dimension_values(x, "time")
x_agg_time = aggregate(x, by = t1 + c(0, 2, 4), FUN = max) 

# aggregate time dimension in format Date - interval
by_t = "2 days"
x_agg_time2 = aggregate(x, by = by_t, FUN = max) 
st_get_dimension_values(x_agg_time2, "time")
#TBD:
#x_agg_time - x_agg_time2

# aggregate time dimension in format POSIXct
x = st_set_dimensions(x, 4, values = as.POSIXct(c("2018-07-31", 
                                                  "2018-08-01", 
                                                  "2018-08-02", 
                                                  "2018-08-03")), 
                      names = "time")
by_t = as.POSIXct(c("2018-07-31", "2018-08-02"))
x_agg_posix = aggregate(x, by = by_t, FUN = max)
st_get_dimension_values(x_agg_posix, "time")
#TBD:
# x_agg_time - x_agg_posix
aggregate(x, "2 days", mean)
if (require(ncmeta, quietly = TRUE)) {
 # Spatial aggregation, see https://github.com/r-spatial/stars/issues/299
 prec_file = system.file("nc/test_stageiv_xyt.nc", package = "stars")
 prec = read_ncdf(prec_file, curvilinear = c("lon", "lat"))
 prec_slice = dplyr::slice(prec, index = 17, along = "time")
 nc = sf::read_sf(system.file("gpkg/nc.gpkg", package = "sf"), "nc.gpkg")
 nc = st_transform(nc, st_crs(prec_slice))
 agg = aggregate(prec_slice, st_geometry(nc), mean)
 plot(agg)
}

# example of using a function for "by": aggregate by month-of-year
d = c(10, 10, 150)
a = array(rnorm(prod(d)), d) # pure noise
times = Sys.Date() + seq(1, 2000, length.out = d[3])
m = as.numeric(format(times, "\%m"))
signal = rep(sin(m / 12 * pi), each = prod(d[1:2])) # yearly period
s = (st_as_stars(a) + signal) |>
      st_set_dimensions(3, values = times)
f = function(x, format = "\%B") {
	  months = format(as.Date(paste0("01-", 1:12, "-1970")), format)
	  factor(format(x, format), levels = months)
}
agg = aggregate(s, f, mean)
plot(agg)

\donttest{
# exact = TRUE with secondary weights: population-weighted mean
# population density per municipality
if (requireNamespace("exactextractr", quietly = TRUE) &&
    requireNamespace("terra", quietly = TRUE)) {
  dens = read_stars(system.file("sao_miguel/gpw_v411_2020_density_2020.tif", 
     package = "exactextractr"))
  pop = read_stars(system.file("sao_miguel/gpw_v411_2020_count_2020.tif", 
     package = "exactextractr"))
  conc = sf::read_sf(system.file("sao_miguel/concelhos.gpkg", 
     package = "exactextractr"))
  aggregate(dens, conc, mean, exact = TRUE, weights = pop, na.rm = TRUE)
}
} # donttest
}
\seealso{
\link[sf]{aggregate}, \link[sf]{st_interpolate_aw}, \link{st_extract}, https://github.com/r-spatial/stars/issues/317
}
