Title: Support for Spatial Objects Within the 'mlr3' Ecosystem
Version: 0.6.0
Date: 2025-07-18
Description: Extends the 'mlr3' ML framework with methods for spatial objects. Data storage and prediction are supported for packages 'terra', 'raster' and 'stars'.
License: LGPL-3
URL: https://mlr3spatial.mlr-org.com, https://github.com/mlr-org/mlr3spatial
BugReports: https://github.com/mlr-org/mlr3spatial/issues
Depends: mlr3 (≥ 0.14.0), R (≥ 3.1.0)
Imports: checkmate (≥ 2.0.0), data.table (≥ 1.14.0), lgr (≥ 0.4.2), methods, mlr3misc (≥ 0.11.0), R6 (≥ 2.5.0), sf, terra (≥ 1.6-3), utils
Suggests: bench, future, future.callr, knitr, mlr3learners (≥ 0.4.5), paradox, ranger, raster, rmarkdown, rpart, stars (≥ 0.5-5), testthat (≥ 3.0.0)
VignetteBuilder: knitr
Config/testthat/edition: 3
Config/testthat/parallel: false
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.3.2
Collate: 'DataBackendRaster.R' 'DataBackendVector.R' 'LearnerClassifSpatial.R' 'LearnerRegrSpatial.R' 'TaskRegrST.R' 'TaskClassifST.R' 'TaskClassif_leipzig.R' 'as_task_classif_st.R' 'as_task_regr_st.R' 'as_task_unsupervised.R' 'data.R' 'helper.R' 'predict_spatial.R' 'zzz.R'
NeedsCompilation: no
Packaged: 2025-07-18 09:59:29 UTC; marc
Author: Marc Becker ORCID iD [aut, cre], Patrick Schratz ORCID iD [aut]
Maintainer: Marc Becker <marcbecker@posteo.de>
Repository: CRAN
Date/Publication: 2025-07-18 10:50:02 UTC

mlr3spatial: Support for Spatial Objects Within the 'mlr3' Ecosystem

Description

logo

Extends the 'mlr3' ML framework with methods for spatial objects. Data storage and prediction are supported for packages 'terra', 'raster' and 'stars'.

Learn mlr3

mlr3 extensions

Suggested packages

Package Options

Author(s)

Maintainer: Marc Becker marcbecker@posteo.de (ORCID)

Authors:

References

Becker M, Schratz P (2024). mlr3spatial: Support for Spatial Objects Within the 'mlr3' Ecosystem. R package version 0.6.0, https://mlr3spatial.mlr-org.com.

See Also

Useful links:


DataBackend for Raster Objects

Description

mlr3::DataBackend for terra::SpatRaster raster objects.

Read mode

There are two different ways the reading of values is performed internally:

"Block mode" is activated if ⁠$data(rows)⁠ is used with a increasing integer sequence e.g. 200:300. If only a single cell is requested, "cell mode" is used.

Super class

mlr3::DataBackend -> DataBackendRaster

Active bindings

rownames

(integer())
Returns vector of all distinct row identifiers, i.e. the contents of the primary key column.

colnames

(character())
Returns vector of all column names.

nrow

(integer(1))
Number of rows (observations).

ncol

(integer(1))
Number of columns (variables).

stack

(SpatRaster)
Raster stack.

Methods

Public methods

Inherited methods

Method new()

Creates a new instance of this R6 class.

Usage
DataBackendRaster$new(data)
Arguments

Method data()

Returns a slice of the raster in the specified format. Currently, the only supported formats is "data.table".

The rows must be addressed as vector of cells indices, columns must be referred to via layer names. Queries for rows with no matching row id and queries for columns with no matching column name are silently ignored.

Rows are guaranteed to be returned in the same order as rows, columns may be returned in an arbitrary order. Duplicated row ids result in duplicated rows, duplicated column names lead to an exception.

Usage
DataBackendRaster$data(rows, cols, data_format = "data.table")
Arguments
rows

integer()
Row indices. Row indices start with 1 in the upper left corner in the raster, increase from left to right and then from top to bottom. The last cell is in the bottom right corner and the row index equals the number of cells in the raster.

cols

character()
Column names.

data_format

(character(1))
Desired data format. Currently only "data.table" supported.


Method head()

Retrieve the first n rows.

Usage
DataBackendRaster$head(n = 6L)
Arguments
n

(integer(1))
Number of rows.

Returns

data.table::data.table() of the first n rows.


Method distinct()

Returns a named list of vectors of distinct values for each column specified. If na_rm is TRUE, missing values are removed from the returned vectors of distinct values. Non-existing rows and columns are silently ignored.

Usage
DataBackendRaster$distinct(rows, cols, na_rm = TRUE)
Arguments
rows

integer()
Row indices. Row indices start with 1 in the upper left corner in the raster, increase from left to right and then from top to bottom. The last cell is in the bottom right corner and the row index equals the number of cells in the raster.

cols

character()
Column names.

na_rm

logical(1)
Whether to remove NAs or not.

Returns

Named list() of distinct values.


Method missings()

Returns the number of missing values per column in the specified slice of data. Non-existing rows and columns are silently ignored.

Usage
DataBackendRaster$missings(rows, cols)
Arguments
rows

integer()
Row indices. Row indices start with 1 in the upper left corner in the raster, increase from left to right and then from top to bottom. The last cell is in the bottom right corner and the row index equals the number of cells in the raster.

cols

character()
Column names.

Returns

Total of missing values per column (named numeric()).


Method coordinates()

Returns the coordinates of rows. If rows is missing, all coordinates are returned.

Usage
DataBackendRaster$coordinates(rows)
Arguments
rows

integer()
Row indices. Row indices start with 1 in the upper left corner in the raster, increase from left to right and then from top to bottom. The last cell is in the bottom right corner and the row index equals the number of cells in the raster.

Returns

data.table::data.table() of coordinates of rows.


DataBackend for Vector Objects

Description

mlr3::DataBackend for sf::sf vector objects.

Super classes

mlr3::DataBackend -> mlr3::DataBackendDataTable -> DataBackendVector

Active bindings

sfc

(sf::sfc)
Returns the sfc object.

Methods

Public methods

Inherited methods

Method new()

Creates a new instance of this R6 class.

Usage
DataBackendVector$new(data, primary_key)
Arguments
data

(sf)
A raster object.

primary_key

(character(1) | integer())
Name of the primary key column, or integer vector of row ids.


Spatiotemporal Classification Task

Description

This task specializes mlr3::TaskClassif for spatiotemporal classification problems.

A spatial example task is available via tsk("ecuador").

The coordinate reference system passed during initialization must match the one which was used during data creation, otherwise offsets of multiple meters may occur. By default, coordinates are not used as features. This can be changed by setting coords_as_features = TRUE.

Super classes

mlr3::Task -> mlr3::TaskSupervised -> mlr3::TaskClassif -> TaskClassifST

Active bindings

crs

(character(1))
Returns coordinate reference system of task.

coordinate_names

(character())
Returns coordinate names.

coords_as_features

(logical(1))
If TRUE, coordinates are used as features.

Methods

Public methods

Inherited methods

Method new()

Creates a new instance of this R6 class. The function as_task_classif_st() provides an alternative way to construct classification tasks.

Usage
TaskClassifST$new(
  id,
  backend,
  target,
  positive = NULL,
  label = NA_character_,
  coordinate_names,
  crs = NA_character_,
  coords_as_features = FALSE,
  extra_args = list()
)
Arguments
id

(character(1))
Identifier for the new instance.

backend

(mlr3::DataBackend)
Either a mlr3::DataBackend, or any object which is convertible to a mlr3::DataBackend with mlr3::as_data_backend(). E.g., am sf will be converted to a mlr3::DataBackendDataTable.

target

(character(1))
Name of the target column.

positive

(character(1))
Only for binary classification: Name of the positive class. The levels of the target columns are reordered accordingly, so that the first element of ⁠$class_names⁠ is the positive class, and the second element is the negative class.

label

(character(1))
Label for the new instance.

coordinate_names

(character(1))
The column names of the coordinates in the data.

crs

(character(1))
Coordinate reference system. WKT2 or EPSG string.

coords_as_features

(logical(1))
If TRUE, coordinates are used as features. This is a shortcut for task$set_col_roles(c("x", "y"), role = "feature") with the assumption that the coordinates in the data are named "x" and "y".

extra_args

(named list())
Named list of constructor arguments, required for converting task types via mlr3::convert_task().


Method coordinates()

Returns coordinates of observations.

Usage
TaskClassifST$coordinates(row_ids = NULL)
Arguments
row_ids

(integer()) Vector of rows indices as subset of task$row_ids.

Returns

data.table::data.table()


Method print()

Print the task.

Usage
TaskClassifST$print(...)
Arguments
...

Arguments passed to the ⁠$print()⁠ method of the superclass.


Method clone()

The objects of this class are cloneable with this method.

Usage
TaskClassifST$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.


Spatiotemporal Regression Task

Description

This task specializes mlr3::TaskRegr for spatiotemporal regression problems.

A spatial example task is available via tsk("cookfarm_mlr3").

The coordinate reference system passed during initialization must match the one which was used during data creation, otherwise offsets of multiple meters may occur. By default, coordinates are not used as features. This can be changed by setting coords_as_features = TRUE.

Super classes

mlr3::Task -> mlr3::TaskSupervised -> mlr3::TaskRegr -> TaskRegrST

Active bindings

crs

(character(1))
Returns coordinate reference system of the task.

coordinate_names

(character())
Returns coordinate names.

coords_as_features

(logical(1))
If TRUE, coordinates are used as features.

Methods

Public methods

Inherited methods

Method new()

Creates a new instance of this R6 class. The function as_task_regr_st() provides an alternative way to construct classification tasks.

Usage
TaskRegrST$new(
  id,
  backend,
  target,
  label = NA_character_,
  coordinate_names,
  crs = NA_character_,
  coords_as_features = FALSE,
  extra_args = list()
)
Arguments
id

(character(1))
Identifier for the new instance.

backend

(mlr3::DataBackend)
Either a mlr3::DataBackend, or any object which is convertible to a mlr3::DataBackend with mlr3::as_data_backend(). E.g., am sf will be converted to a mlr3::DataBackendDataTable.

target

(character(1))
Name of the target column.

label

(character(1))
Label for the new instance.

coordinate_names

(character(1))
The column names of the coordinates in the data.

crs

(character(1))
Coordinate reference system. WKT2 or EPSG string.

coords_as_features

(logical(1))
If TRUE, coordinates are used as features. This is a shortcut for task$set_col_roles(c("x", "y"), role = "feature") with the assumption that the coordinates in the data are named "x" and "y".

extra_args

(named list())
Named list of constructor arguments, required for converting task types via mlr3::convert_task().


Method coordinates()

Returns coordinates of observations.

Usage
TaskRegrST$coordinates(row_ids = NULL)
Arguments
row_ids

(integer())
Vector of rows indices as subset of task$row_ids.

Returns

data.table::data.table()


Method print()

Print the task.

Usage
TaskRegrST$print(...)
Arguments
...

Arguments passed to the ⁠$print()⁠ method of the superclass.


Method clone()

The objects of this class are cloneable with this method.

Usage
TaskRegrST$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.


Coerce to spatial DataBackend

Description

Wraps a mlr3::DataBackend around spatial objects. Currently these S3 methods are only alternative ways for writing DataBackendRaster$new(). They do not support coercing from other backends yet.

Usage

## S3 method for class 'stars'
as_data_backend(data, primary_key = NULL, ...)

## S3 method for class 'SpatRaster'
as_data_backend(data, primary_key = NULL, ...)

## S3 method for class 'RasterBrick'
as_data_backend(data, primary_key = NULL, ...)

## S3 method for class 'RasterStack'
as_data_backend(data, primary_key = NULL, ...)

## S3 method for class 'sf'
as_data_backend(data, primary_key = NULL, keep_rownames = FALSE, ...)

Arguments

data

(terra::SpatRaster)
The input terra::SpatRaster.

primary_key

(character(1) | integer())
Name of the primary key column, or integer vector of row ids.

...

(any)
Not used.

keep_rownames

(logical(1) | character(1))
If TRUE or a single string, keeps the row names of data as a new column. The column is named like the provided string, defaulting to "..rownames" for keep_rownames == TRUE. Note that the created column will be used as a regular feature by the task unless you manually change the column role. Also see data.table::as.data.table().

Value

mlr3::DataBackend.


Convert to a Spatiotemporal Classification Task

Description

Convert object to a TaskClassifST. This is a S3 generic, specialized for at least the following objects:

  1. TaskClassifST: Ensure the identity.

  2. data.frame() and mlr3::DataBackend: Provides an alternative to the constructor of TaskClassifST.

  3. sf::sf: Extracts spatial meta data before construction.

  4. mlr3::TaskRegr: Calls mlr3::convert_task().

Usage

as_task_classif_st(x, ...)

## S3 method for class 'TaskClassifST'
as_task_classif_st(x, clone = FALSE, ...)

## S3 method for class 'data.frame'
as_task_classif_st(
  x,
  target,
  id = deparse(substitute(x)),
  positive = NULL,
  coordinate_names,
  crs = NA_character_,
  coords_as_features = FALSE,
  label = NA_character_,
  ...
)

## S3 method for class 'DataBackend'
as_task_classif_st(
  x,
  target,
  id = deparse(substitute(x)),
  positive = NULL,
  coordinate_names,
  crs,
  coords_as_features = FALSE,
  label = NA_character_,
  ...
)

## S3 method for class 'sf'
as_task_classif_st(
  x,
  target = NULL,
  id = deparse(substitute(x)),
  positive = NULL,
  coords_as_features = FALSE,
  label = NA_character_,
  ...
)

## S3 method for class 'TaskRegrST'
as_task_classif_st(
  x,
  target = NULL,
  drop_original_target = FALSE,
  drop_levels = TRUE,
  ...
)

Arguments

x

(any)
Object to convert.

...

(any)
Additional arguments.

clone

(logical(1))
If TRUE, ensures that the returned object is not the same as the input x.

target

(character(1))
Name of the target column.

id

(character(1))
Id for the new task. Defaults to the (deparsed and substituted) name of the data argument.

positive

(character(1))
Level of the positive class. See TaskClassif.

coordinate_names

(character(1))
The column names of the coordinates in the data.

crs

(character(1))
Coordinate reference system. WKT2 or EPSG string.

coords_as_features

(logical(1))
If TRUE, coordinates are used as features. This is a shortcut for task$set_col_roles(c("x", "y"), role = "feature") with the assumption that the coordinates in the data are named "x" and "y".

label

(character(1))
Label for the new instance.

drop_original_target

(logical(1))
If FALSE (default), the original target is added as a feature. Otherwise the original target is dropped.

drop_levels

(logical(1))
If TRUE (default), unused levels of the new target variable are dropped.

Value

TaskClassifST


Convert to a Spatiotemporal Regression Task

Description

Convert object to a TaskRegrST. This is a S3 generic, specialized for at least the following objects:

  1. TaskRegrST: Ensure the identity.

  2. data.frame() and mlr3::DataBackend: Provides an alternative to the constructor of TaskRegrST.

  3. sf::sf: Extracts spatial meta data before construction.

  4. mlr3::TaskClassif: Calls mlr3::convert_task().

Usage

as_task_regr_st(x, ...)

## S3 method for class 'TaskRegrST'
as_task_regr_st(x, clone = FALSE, ...)

## S3 method for class 'data.frame'
as_task_regr_st(
  x,
  target,
  id = deparse(substitute(x)),
  coordinate_names,
  crs = NA_character_,
  coords_as_features = FALSE,
  label = NA_character_,
  ...
)

## S3 method for class 'DataBackend'
as_task_regr_st(
  x,
  target,
  id = deparse(substitute(x)),
  coordinate_names,
  crs,
  coords_as_features = FALSE,
  label = NA_character_,
  ...
)

## S3 method for class 'sf'
as_task_regr_st(
  x,
  target = NULL,
  id = deparse(substitute(x)),
  coords_as_features = FALSE,
  label = NA_character_,
  ...
)

## S3 method for class 'TaskClassifST'
as_task_regr_st(
  x,
  target = NULL,
  drop_original_target = FALSE,
  drop_levels = TRUE,
  ...
)

Arguments

x

(any)
Object to convert.

...

(any)
Additional arguments.

clone

(logical(1))
If TRUE, ensures that the returned object is not the same as the input x.

target

(character(1))
Name of the target column.

id

(character(1))
Id for the new task. Defaults to the (deparsed and substituted) name of the data argument.

coordinate_names

(character(1))
The column names of the coordinates in the data.

crs

(character(1))
Coordinate reference system. WKT2 or EPSG string.

coords_as_features

(logical(1))
If TRUE, coordinates are used as features. This is a shortcut for task$set_col_roles(c("x", "y"), role = "feature") with the assumption that the coordinates in the data are named "x" and "y".

label

(character(1))
Label for the new instance.

drop_original_target

(logical(1))
If FALSE (default), the original target is added as a feature. Otherwise the original target is dropped.

drop_levels

(logical(1))
If TRUE (default), unused levels of the new target variable are dropped.

Value

TaskRegrST


Split Raster Into Chunks

Description

Splits raster into chunks.

Usage

block_size(raster, chunksize)

Arguments

raster

(terra::SpatRaster)
Raster to be split into chunks.

chunksize

(integer(1))
The chunksize determines in how many subparts the prediction task will be split into. The value can be roughly thought of as megabyte of a raster file on disk. For example, if a prediction on a 1 GB file would be carried out with chunksize = 100L, the prediction would happen in 10 chunks.

The default of chunksize = 1000L might be a good compromise between speed and memory usage. If you find yourself running out of memory, reduce this value.


Factor Layer Generator

Description

Generates a factor layer when passed to generate_stack().

Usage

factor_layer(id, levels, in_memory = FALSE)

Arguments

id

(character(1))
Layer id.

levels

(character())
Factor levels.

in_memory

(logical(1))
If FALSE (default), layer is written to disk.

Value

Named list()


Generate Raster Stack

Description

Generates a raster stack.

Usage

generate_stack(
  layers,
  layer_size = NULL,
  dimension = NULL,
  multi_layer_file = FALSE
)

Arguments

layers

(List of numeric_layer() and factor_layer())
List of layers.

layer_size

(numeric(1))
Size of a single layer in megabytes.

dimension

(integer(1))
Dimension of the squared layers.

multi_layer_file

(logical(1))
If TRUE, raster is written to disk as a single multi-layer file. Overwrites ìn_memory argument of numeric_layer() and factor_layer().

layer_size and dimension are mutually exclusive.

Value

terra::SpatRaster


Leipzig Land Cover Task

Description

Point survey of land cover in Leipzig. Includes Sentinel-2 spectral bands and NDVI.

Source

Copernicus Sentinel Data (2021). Retrieved from Copernicus Open Access Hub and processed by European Space Agency.

Examples

if (requireNamespace("sf")) {
  library(sf)
  data("leipzig", package = "mlr3spatial")
  print(leipzig)
}

Sample Points in Raster Stack

Description

Masks stack to a circular area of interest.

Usage

mask_stack(stack)

Arguments

stack

(terra::SpatRaster)
Raster stack.

Value

terra::SpatRaster


Numeric Layer Generator

Description

Generates a numeric layer when passed to generate_stack().

Usage

numeric_layer(id, in_memory = FALSE)

Arguments

id

(character(1))
Layer id.

in_memory

(logical(1))
If FALSE (default), layer is written to disk.

Value

Named list()


Predict on Spatial Objects with mlr3 Learners

Description

This function allows to directly predict mlr3 learners on various spatial objects.

Usage

predict_spatial(
  newdata,
  learner,
  chunksize = 200L,
  format = "terra",
  filename = NULL
)

Arguments

newdata

(terra::SpatRaster | stars::stars | sf::sf | raster::RasterStack | raster::RasterBrick). New data to predict on. All spatial data formats convertible by as_data_backend() are supported e.g. terra::SpatRaster or sf::sf.

learner

(mlr3::Learner). Learner with trained model.

chunksize

(integer(1))
The chunksize determines in how many subparts the prediction task will be split into. The value can be roughly thought of as megabyte of a raster file on disk. For example, if a prediction on a 1 GB file would be carried out with chunksize = 100L, the prediction would happen in 10 chunks.

The default of chunksize = 1000L might be a good compromise between speed and memory usage. If you find yourself running out of memory, reduce this value.

format

(character(1))
Output class of the resulting object. Accepted values are "raster", "stars" and "terra" if the input is a raster. Note that when choosing something else than "terra", the spatial object is converted into the respective format which might cause overhead both in runtime and memory allocation. For vector data only "sf" is supported.

filename

(character(1))
Path where the spatial object should be written to.

Value

Spatial object of class given in argument format.

Examples

library(terra, exclude = "resample")

# fit rpart on training points
task_train = tsk("leipzig")
learner = lrn("classif.rpart")
learner$train(task_train)

# load raster
stack = rast(system.file("extdata", "leipzig_raster.tif", package = "mlr3spatial"))

# predict land cover classes
pred = predict_spatial(stack, learner, chunksize = 1L)

Sample Points in Raster Stack

Description

Samples n points of a raster stack.

Usage

sample_stack(stack, n = 100)

Arguments

stack

(terra::SpatRaster)
Raster stack.

n

(integer(1))
Number of points.

Value

sf::sf


Write a Raster in Chunks

Description

Writes square raster to disk in chunks. Internal helper function.

Usage

write_raster(data)

Arguments

data

⁠[SpatRaster]⁠
SpatRaster object.