apply_time.cube: Apply a user-defined R function over (multi-band) pixel time...

View source: R/apply_time.R

apply_time.cubeR Documentation

Apply a user-defined R function over (multi-band) pixel time series


Create a proxy data cube, which applies a user-defined R function over all pixel time series of a data cube. In contrast to reduce_time, the time dimension is not reduced, i.e., resulting time series must have identical length as the input data cube but may contain a different number of bands / variables. Example uses of this function may include time series decompositions, cumulative sums / products, smoothing, sophisticated NA filling, or similar.


## S3 method for class 'cube'
apply_time(x, names = NULL, keep_bands = FALSE, FUN, ...)



source data cube


optional character vector to specify band names for the output cube


logical; keep bands of input data cube, defaults to FALSE, i.e., original bands will be dropped


user-defined R function that is applied on all pixel time series (see Details)


not used


FUN receives a single (multi-band) pixel time series as a matrix with rows corresponding to bands and columns corresponding to time. In general, the function must return a matrix with the same number of columns. If re result contains only a single band, it may alternatively return a vector with length identical to the length of the input time series (number of columns of the input).


a proxy data cube object


This function returns a proxy object, i.e., it will not start any computations besides deriving the shape of the result.


# create image collection from example Landsat data only 
# if not already done in other examples
if (!file.exists(file.path(tempdir(), "L8.db"))) {
  L8_files <- list.files(system.file("L8NY18", package = "gdalcubes"),
                         ".TIF", recursive = TRUE, full.names = TRUE)
  create_image_collection(L8_files, "L8_L1TP", file.path(tempdir(), "L8.db"), quiet = TRUE) 

L8.col = image_collection(file.path(tempdir(), "L8.db"))
v = cube_view(extent=list(left=388941.2, right=766552.4, 
              bottom=4345299, top=4744931, t0="2018-01", t1="2018-06"),
              srs="EPSG:32618", nx = 497, ny=526, dt="P1M")
L8.cube = raster_cube(L8.col, v) 
L8.cube = select_bands(L8.cube, c("B04", "B05")) 
L8.ndvi = apply_pixel(L8.cube, "(B05-B04)/(B05+B04)", "NDVI")

# Apply a user defined R function
L8.ndvi.resid = apply_time(L8.ndvi, names="NDVI_residuals", 
   FUN=function(x) {
      y = x["NDVI",]
      if (sum(is.finite(y)) < 3) {
      t = 1:ncol(x)
      return(predict(lm(y ~ t)) -  x["NDVI",])



gdalcubes documentation built on April 14, 2023, 5:08 p.m.