Skip to content
Prev 29320 / 29559 Next

Counting points in cells and ploting only cells containing points

Here is one approach. Kind of a silly example with just one grid cell, but
would work with more polygons and more points.


library(sf)
library(tidyverse)

# make some points data
# modified example from
# https://r-spatial.github.io/sf/reference/geos_binary_pred.html
(pts <-
    st_sfc(st_point(c(.5,.5)), st_point(c(1.5, 1.5)), st_point(c(2.5,
2.5))) |>
    st_as_sf()|>
    rowid_to_column(var = 'pts_id'))

(pol <-
    st_polygon(list(rbind(c(0,0), c(2,0), c(2,2), c(0,2), c(0,0)))) |>
    st_sfc() |>
    st_as_sf()|>
    rowid_to_column(var = 'pol_id')
  )

# look at the data, crude 'map'
plot(pts); plot(pol, add = TRUE) # take a look

# perform the intersection
pts_pol_int <-
  pts |>
  st_intersection(pol) # only going to retain the overlaps (drops
non-intersecting elements)

# count the overlaps
cont_pts_pol_int <-
  pts_pol_int |>
  st_drop_geometry() |> # pulls out the data frame (or tibble)
  group_by(pol_id) |>
  count()

cont_pts_pol_int # could be joined back to pol

HTH, DHL


On Wed, Nov 22, 2023 at 6:39?AM MIGUEL GOMEZ DE ANTONIO <mga at ccee.ucm.es>
wrote: