How summarise spatial data, based on shapefiles?

Viewed 25

I am trying to collect data from entire neighborhoods, which I have segregated into houses. There is no identifier within the bases that relates them, only that when you place their shapefiles on top of each other, you find this house-neighborhood relationship.

I wanted to know if R has some function that spatially identifies these overlaps, and you can make a kind of summarize, as it is done with normal df.

1 Answers

Here is how you can do a point-in-polygon query with "terra"

Example data

library(terra)
f <- system.file("ex/lux.shp", package="terra")
ngbs <- vect(f)
ngbs <- ngbs[,"NAME_2"]
set.seed(1)
houses <- spatSample(ngbs, 100)
values(houses) <- NULL
houses$size <- sample(1000:2000, 100)
houses$price <- sample(200000:400000, 100)

Solution

e <- extract(ngbs, houses, ID=FALSE)
hn <- cbind(e, houses)
aggregate(hn[, c("size", "price")], hn[, "NAME_2", drop=FALSE], mean, na.rm=TRUE)
#             NAME_2     size    price
#1          Capellen 1426.111 313185.0
#2          Clervaux 1576.143 283965.4
#3          Diekirch 1690.333 305811.3
#4        Echternach 1372.375 252986.4
#5  Esch-sur-Alzette 1535.696 306376.3
#6      Grevenmacher 1491.333 326899.4
#7        Luxembourg 1635.222 273848.1
#8            Mersch 1360.636 305946.5
#9           Redange 1620.000 282540.8
#10           Remich 1801.000 314103.0
#11          Vianden 1403.000 312586.0
#12            Wiltz 1625.000 260969.2

Or possibly do

ints <- intersect(houses, ngbs)
ints
# class       : SpatVector 
# geometry    : points 
# dimensions  : 100, 3  (geometries, attributes)
# extent      : 5.754352, 6.489788, 49.47263, 50.09873  (xmin, xmax, ymin, ymax)
# coord. ref. : lon/lat WGS 84 (EPSG:4326) 
# names       :  size  price   NAME_2
# type        : <int>  <int>    <chr>
# values      :  1678 239240 Diekirch
#                1128 379030   Mersch
#                1929 359349 Diekirch
Related