Thursday 20 April 2017

sp - Counting number of points in polygon using R?


I have two classes sharing the same CRS (Latitute and Longitude):



  1. bolognaQuartieriMap: a SpatialPolygonDataFrame containing data of a city boroughts.

  2. crashPoints: a SpatialPointsDataFrame containing data of accidents.


They are well plotted using:


plot(bolognaQuartieriMap)
title("Crash per quartiere")
plot(crashPoints, col="red",add=TRUE)


What I need is to get the number of points (crashPoints) in each polygon that constitute bolognaQuartieriMap. I was suggested to use over() but I did not succeed.



Answer



Since you didn't provide a reproducible example nor an error message, see if this code snippet gets you started:


library("raster")
library("sp")

x <- getData('GADM', country='ITA', level=1)
class(x)
# [1] "SpatialPolygonsDataFrame"

# attr(,"package")
# [1] "sp"

set.seed(1)
# sample random points
p <- spsample(x, n=300, type="random")
p <- SpatialPointsDataFrame(p, data.frame(id=1:300))

proj4string(x)
# [1] " +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"

proj4string(p)
# [1] " +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"

plot(x)
plot(p, col="red" , add=TRUE)

plot


res <- over(p, x)
table(res$NAME_1) # count points
# Abruzzo Apulia Basilicata

# 11 20 9
# Calabria Campania Emilia-Romagna
# 16 8 25
# Friuli-Venezia Giulia Lazio Liguria
# 7 14 7
# Lombardia Marche Molise
# 22 4 3
# Piemonte Sardegna Sicily
# 35 18 21
# Toscana Trentino-Alto Adige Umbria

# 33 15 6
# Valle d'Aosta Veneto
# 4 22

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...