Learn R Programming

tidyterra (version 1.3.0)

rowwise.SpatVector: Group SpatVector objects by rows

Description

rowwise() lets you compute on a SpatVector one row at a time. This is most useful when a vectorised function does not exist.

Most dplyr verb implementations in tidyterra preserve row-wise grouping. The exception is summarise.SpatVector(), which returns a grouped SpatVector. You can explicitly ungroup with ungroup.SpatVector() or as_tibble() or convert to a grouped SpatVector with group_by.SpatVector().

Usage

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

Value

The same SpatVector object with updated grouping metadata.

Arguments

data

A SpatVector object. See Methods.

...

<tidy-select> Variables to be preserved when calling summarise.SpatVector(). This is typically a set of variables whose combination uniquely identifies each row. See dplyr::rowwise().

Unlike group_by.SpatVector(), you cannot create new variables here. Instead, you can select multiple variables, for example with everything().

Methods

Implementation of the generic dplyr::rowwise() method for SpatVector objects.

Grouping metadata

Mixing terra and dplyr syntax on a grouped or row-wise SpatVector, for example by subsetting with v[1:3, 1:2], can corrupt its grouping metadata. tidyterra attempts to restore this metadata the next time you use a dplyr verb on the object.

Some operations, such as terra::spatSample(), create a new SpatVector without preserving grouping metadata. Call group_by.SpatVector() or rowwise.SpatVector() again, as appropriate.

Details

See Details on dplyr::rowwise().

See Also

dplyr::rowwise().

Other dplyr verbs that operate on groups of rows: count.SpatVector(), group_by.SpatVector(), reframe.SpatVector(), summarise.SpatVector()

Examples

Run this code
library(terra)
library(dplyr)

v <- terra::vect(system.file("shape/nc.shp", package = "sf"))

# Select new births
nb <- v |>
  select(starts_with("NWBIR")) |>
  glimpse()

# Compute the mean of NWBIR for each geometry.
nb |>
  rowwise() |>
  mutate(nb_mean = mean(c(NWBIR74, NWBIR79)))

# Additional examples
# \donttest{
# Use c_across() to select many variables more easily.
nb |>
  rowwise() |>
  mutate(m = mean(c_across(NWBIR74:NWBIR79)))

# Compute the minimum of x and y in each row

nb |>
  rowwise() |>
  mutate(min = min(c_across(NWBIR74:NWBIR79)))

# Summarize.
v |>
  rowwise() |>
  summarise(mean_bir = mean(BIR74, BIR79)) |>
  glimpse() |>
  autoplot(aes(fill = mean_bir))

# Supply a variable to be kept
v |>
  mutate(id2 = as.integer(CNTY_ID / 100)) |>
  rowwise(id2) |>
  summarise(mean_bir = mean(BIR74, BIR79)) |>
  glimpse() |>
  autoplot(aes(fill = as.factor(id2)))
# }

Run the code above in your browser using DataLab