pull() is similar to $ on a data frame. It is mostly useful because it
looks nicer in pipes and can optionally name the output.
You can extract the cell-center coordinates of a SpatRaster
in its CRS.
Use pull(.data, x, xy = TRUE). x and y are reserved
names in terra, since they refer to cell coordinates.
See Examples and section Layer and column names on
as_tibble.Spat().
Arguments
- .data
A
SpatRastercreated withterra::rast()or aSpatVectorcreated withterra::vect().- var
A variable specified as:
a literal layer/attribute name.
a positive integer, giving the position counting from the left.
a negative integer, giving the position counting from the right.
The default returns the last layer/attribute (on the assumption that's the column you've created most recently).
This argument is taken by expression and supports quasiquotation (you can unquote column names and column locations).
- name
An optional parameter that specifies the column to be used as names for a named vector. Specified in a similar manner as
var.- ...
Arguments passed to
as_tibble.SpatRaster()oras_tibble.Spat()methods.
Value
A vector with one element per cell or geometry in .data. For
SpatRaster objects, the default (na.rm = FALSE) keeps
missing values.
Passing na.rm = TRUE to ... omits cells with a missing value in any
layer and can shorten the result. See terra::as.data.frame().
terra equivalent
Methods
Implementation of the generic dplyr::pull() methods. Each method first
coerces the Spat* object to a tibble (see
as_tibble.Spat) and then
applies dplyr::pull() to the tibble.
SpatRaster
With xy = TRUE, x and y are the first two columns and give the
cell-center coordinates in the raster's CRS. For example, pull(.data, 1)
returns the first layer's values, and pull(.data, 1, xy = TRUE) returns
the cells' x coordinates.
SpatVector
When passing geom = "WKT" or geom = "HEX" to ..., the geometry of the
SpatVector can be extracted with var = geometry.
Similarly, when using
geom = "XY", the coordinates can be extracted with var = x or
var = y. See the options in terra::as.data.frame().
See also
Other dplyr verbs that operate on columns:
glimpse.Spat,
mutate.Spat,
relocate.Spat,
rename.Spat,
select.Spat
Examples
library(terra)
f <- system.file("extdata/cyl_tile.tif", package = "tidyterra")
r <- rast(f)
# Extract the second layer.
r |>
pull(2) |>
head()
#> [1] 229 235 229 229 239 153
# Extract the y coordinate of each cell in the raster's CRS.
r |>
pull(2, xy = TRUE) |>
head()
#> [1] 5370160 5370160 5370160 5370160 5370160 5370160
# With renaming
r |>
mutate(cat = cut(cyl_tile_3, c(0, 100, 300))) |>
pull(cyl_tile_3, name = cat) |>
head()
#> (100,300] (100,300] (100,300] (100,300] (100,300] (100,300]
#> 206 224 206 206 233 169
