Provide the 'cellnumbers' capability of raster::extract and friends directly, returning a data frame of query-object identifiers 'object_' and the cell number.
cellnumbers(x, query, ...)
# S3 method for default
cellnumbers(x, query, ...)
# S3 method for SpatialLines
cellnumbers(x, query, ...)
# S3 method for sfc
cellnumbers(x, query, ...)
# S3 method for sf
cellnumbers(x, query, ...)
Raster object
Spatial object or matrix of coordinates
unused
a data frame (tibble) with columns
object_
- the object ID (what row is it from the spatial object)
cell_
- the cell number of the raster
Raster data is inherently 2-dimensional, with a time or 'level' dimension treated like a layers of these 2D forms. The 'raster' package cell number is counted from 1 at the top-left, across the rows and down. This corresponds the the standard "raster graphics" convention used by 'GDAL' and the 'sp' package, and many other implementations. Note that this is different to the convention used by the graphics::image function.
Currently this function only operates as if the input is a single layer objects, it's not clear if adding an extra level of grouping for layers would be sensible.
library(raster)
#> Loading required package: sp
library(dplyr)
#>
#> Attaching package: ‘dplyr’
#> The following objects are masked from ‘package:raster’:
#>
#> intersect, select, union
#> The following objects are masked from ‘package:stats’:
#>
#> filter, lag
#> The following objects are masked from ‘package:base’:
#>
#> intersect, setdiff, setequal, union
r <- raster(volcano) %>% aggregate(fact = 4)
cellnumbers(r, rasterToContour(r, level = 120))
#> # A tibble: 64 × 2
#> object_ cell_
#> <int> <int>
#> 1 1 8
#> 2 1 9
#> 3 1 10
#> 4 1 11
#> 5 1 21
#> 6 1 22
#> 7 1 23
#> 8 1 24
#> 9 1 27
#> 10 1 28
#> # ℹ 54 more rows
library(dplyr)
cr <- cut(r, pretty(values(r)))
suppressWarnings(tt <- cellnumbers(cr, polycano))
#> projections not the same
#> x: NA
#> query: NAFALSE
#> cellnumbers is very slow for SpatialPolygons, consider conversion with 'sf::st_as_sf'
library(dplyr)
tt %>% mutate(v = extract(r, cell_)) %>%
group_by(object_) %>%
summarize(mean(v))
#> # A tibble: 7 × 2
#> object_ `mean(v)`
#> <int> <dbl>
#> 1 1 157.
#> 2 2 173.
#> 3 3 184
#> 4 4 99.5
#> 5 5 113.
#> 6 6 128.
#> 7 7 142.
head(pretty(values(r)), -1)
#> [1] 80 100 120 140 160 180