Learn R Programming

tidyterra (version 1.3.0)

drop_na.Spat: Drop attributes of Spat* objects containing missing values

Description

  • SpatVector: drop_na() method drops geometries where any attribute specified by ... contains a missing value.

  • SpatRaster: drop_na() method drops cells where any layer specified by ... contains a missing value.

Usage

# S3 method for SpatVector
drop_na(data, ...)

# S3 method for SpatRaster drop_na(data, ...)

Value

A Spat* object of the same class as data. See Methods.

Arguments

data

A SpatVector created with terra::vect() or a SpatRaster terra::rast().

...

<tidy-select> Attributes to inspect for missing values. If empty, all attributes are used.

<a href="https://CRAN.R-project.org/package=terra"><span class="pkg">terra</span></a> equivalent

terra::trim().

Methods

Implementation of the generic tidyr::drop_na() methods for Spat* objects.

SpatVector

This method operates on attributes, meaning that NA values are assessed in the attributes (columns) of each geometry (row). The result is a SpatVector with potentially fewer geometries than the input.

SpatRaster

[Questioning]

The implementation of drop_na.SpatRaster() can be understood as a masking method based on the values of the layers (see terra::mask()).

SpatRaster layers are treated as columns and SpatRaster cells as rows, so rows (cells) with any NA value on any layer become NA. You can also mask the cells (rows) based on the values of specific layers (columns).

drop_na() effectively removes outer cells that are NA (see terra::trim()), so the extent of the resulting object may differ from the extent of the input (see terra::resample() for more information).

Check the Examples to have a better understanding of this method.

Feedback needed!

Visit https://github.com/dieghernan/tidyterra/issues. The implementation of this method for SpatRaster may change in the future.

See Also

tidyr::drop_na().

Other tidyr verbs for handling missing values: complete.SpatVector(), expand.SpatVector(), fill.SpatVector(), replace_na.Spat

Examples

Run this code

library(terra)

f <- system.file("extdata/cyl.gpkg", package = "tidyterra")

v <- terra::vect(f)

# Add missing values.
v <- v |> mutate(iso2 = ifelse(cpro <= "09", NA, cpro))

# Initial plot.
plot(v, col = "red")

# Drop geometries with missing values in iso2.
v |>
  drop_na(iso2) |>
  plot(col = "red")
# SpatRaster method

# \donttest{
r <- rast(
  crs = "EPSG:3857",
  extent = c(0, 10, 0, 10),
  nlyr = 3,
  resolution = c(2.5, 2.5)
)
terra::values(r) <- seq_len(ncell(r) * nlyr(r))

# Add missing values.
r[r > 13 & r < 22 | r > 31 & r < 45] <- NA

# Initial plot.
plot(r, nc = 3)

# Mask with lyr.1.
r |>
  drop_na(lyr.1) |>
  plot(nc = 3)

# Mask with lyr.2.
r |>
  drop_na(lyr.2) |>
  plot(nc = 3)

# Mask with lyr.3.
r |>
  drop_na(lyr.3) |>
  plot(nc = 3)

# Mask all layers.
r |>
  drop_na() |>
  plot(nc = 3)
# }

Run the code above in your browser using DataLab