Skip to content
Prev 27263 / 29559 Next

Spatial join/intersection in R

On 5/6/19 12:23 PM, Edzer Pebesma wrote:
That was too quick: raster::extract returns cell values,
stars::st_intersects returns cell indexes. If we fill the raster with
values 100:1 rather than 1:100, we see

library(stars)
# Loading required package: abind
# Loading required package: sf
# Linking to GEOS 3.7.0, GDAL 2.4.0, PROJ 5.2.0

# create 10 x 10 raster
st_as_stars(matrix(100:1, 10, 10)) %>%
	st_set_dimensions(names = c("x", "y")) %>%
	st_set_dimensions("x", values = 0:9) %>%
	st_set_dimensions("y", values = 9:0) -> r

# three points: at node, edge, and inside cell:
p3 = st_sfc(st_point(c(1,1)), st_point(c(1, 1.5)), st_point(c(1.1, 1.8)))

st_intersects(r, p3, transpose = TRUE)
# Sparse geometry binary predicate list of length 3, where the predicate
was `intersects'
#  1: 82
#  2: 72
#  3: 72
library(raster)
# Loading required package: sp
extract(as(r, "Raster"), as(p3, "Spatial"))
# [1] 19 29 29