How to add a column with location-based data to a SpatialPolygonsDataFrame in R?

放肆的年华 提交于 2019-12-02 05:22:52

I'm not very experienced with spatial data, however, maybe you can use this as a starter:

library(sp)
library(raster)
library(rgeos)

# load map
d <- getData("GADM", country = "Germany", level = 2)

# generate some random points 
set.seed(1)
p <- data.frame(
  lon = jitter(sample(8:13, 20, T)), 
  lat = jitter(sample(49:52, 20, T))
)

# match points with polygons
mat <- gContains(d, SpatialPoints(p, proj4string=CRS(sp::proj4string(d))), byid=TRUE)
hits <- colSums(mat)
cols <- rev(heat.colors(diff(range(hits))+1))

# plot
plot(d, col = cols[hits+1], border = "green")
with(p, points(lon, lat, col = "blue", pch = 19, cex = .5))

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!