Naama
Naama

Reputation: 63

Crating Kernel density estimate for polygon in R

I Have a shapefile of polygons and another one of points that are distributed over the polygons. I would like to create a kernel density estimate for each polygon based on the points it contains. unfortunately I was only able to create squared KDEs with the kde2d function from the MASS package. I would like the KDEs to be shaped as the polygons. Any suggestions?

 kde1 <- kde2d(poly$X, poly$Y, n=100,)

enter image description here

Upvotes: 2

Views: 1069

Answers (2)

Naama
Naama

Reputation: 63

OK! I managed to use my own points by using the 'ppp' function from the spatstat package.

  C <- as.owin(polygon$geometry[n])

  p<- ppp(points$X,points$Y, window = C)

  D <- density(p)
[enter image description here][1]


  [1]: https://i.sstatic.net/YZN0V.png

Upvotes: 0

Ege Rubak
Ege Rubak

Reputation: 4507

You can use the spatstat package for this. Here is an example of reading in a shapefile from sf, generating random points and run kernel density estimation of the intensity of points (points per unit area):

library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
nc <- st_read(system.file("shape/nc.shp", package="sf"))
#> Reading layer `nc' from data source `/usr/lib/R/site-library/sf/shape/nc.shp' using driver `ESRI Shapefile'
#> Simple feature collection with 100 features and 14 fields
#> geometry type:  MULTIPOLYGON
#> dimension:      XY
#> bbox:           xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> geographic CRS: NAD27
nc_flat <- st_transform(nc, crs = 26917)
W <- as.owin(nc_flat$geometry[1]) # First county of North Carolina data set in spatstat format

library(spatstat)
X <- runifpoint(100, win = W)
plot(X, "Random points")

D <- density(X)
plot(D, main = "KDE")

Upvotes: 3

Related Questions