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

半城伤御伤魂 提交于 2019-12-02 07:58:57

问题


I have spatial data in R which is loaded as a SpatialPolygonsDataFrame:

library(sp)
library(tmap)
d <- readRDS("data.rds")
qtm(d)

For the example, I used data for Germany from http://www.gadm.org/download.

Below, you see the map plotted by qtm(d). However, I would like to display my own data. I have locations with longitude and lattitude, and I would like to count the number of points inside the mapped polygons and show those counts as the color of the map below.

I have no clue where to start. Is there a simple approach that maps locations to the polygons?


回答1:


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))



来源:https://stackoverflow.com/questions/33067051/how-to-add-a-column-with-location-based-data-to-a-spatialpolygonsdataframe-in-r

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