I have two classes sharing the same CRS (Latitute and Longitude):
bolognaQuartieriMap
: aSpatialPolygonDataFrame
containing data of a city boroughts.crashPoints
: aSpatialPointsDataFrame
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)
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