rowwise.SpatVector {tidyterra}R Documentation

Group SpatVector objects by rows

Description

rowwise() allows you to compute on a SpatVector a row-at-a-time. This is most useful when a vectorised function doesn't exist.

Most dplyr verbs implementation in tidyterra preserve row-wise grouping, with the exception of summarise.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 class 'SpatVector'
rowwise(data, ...)

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 identify each row. See dplyr::rowwise().

Details

See Details on dplyr::rowwise().

Value

The same SpatVector object with an additional attribute.

Methods

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

When mixing terra and dplyr syntax on a row-wise SpatVector (i.e, subsetting a SpatVector like v[1:3,1:2]) the groups attribute can be corrupted. tidyterra would try to re-generate the SpatVector. This would be triggered the next time you use a dplyr verb on your SpatVector.

Note also that some operations (as terra::spatSample()) would create a new SpatVector. In these cases, the result won't preserve the groups attribute. Use rowwise.SpatVector() to re-group.

See Also

dplyr::rowwise()

Other dplyr verbs that operate on group of rows: count.SpatVector(), group-by.SpatVector, summarise.SpatVector()

Other dplyr methods: arrange.SpatVector(), bind_cols.SpatVector, bind_rows.SpatVector, count.SpatVector(), distinct.SpatVector(), filter-joins.SpatVector, filter.Spat, glimpse.Spat, group-by.SpatVector, mutate-joins.SpatVector, mutate.Spat, pull.Spat, relocate.Spat, rename.Spat, select.Spat, slice.Spat, summarise.SpatVector()

Examples

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 on each geometry
nb %>%
  rowwise() %>%
  mutate(nb_mean = mean(c(NWBIR74, NWBIR79)))

# Additional examples

# use c_across() to more easily select many variables
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)))

# Summarising
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)))


[Package tidyterra version 0.6.0 Index]