如何添加一个基于位置的数据列到R中的SpatialPolygonsDataFrame? [英] How to add a column with location-based data to a SpatialPolygonsDataFrame in R?
问题描述
我有R中的空间数据作为 SpatialPolygonsDataFrame
加载:
library(sp)
/ pre>
库(tmap)
d< - readRDS(data.rds)
qtm(d)
例如,我使用的数据来自
解决方案我对空间数据不是很有经验,但是,也许你可以使用它作为起始点:
库(栅格)
库(rgeos)
#load map
d< - getData(GADM country =Germany,level = 2)
#生成一些随机点
set.seed(1)
p< - data.frame(
lon =抖动(样本(8:13,20,T)),
lat =抖动(样本(49:52,20,T))
)
#多边形
mat< - gContains(d,SpatialPoints(p,proj4string = CRS(sp :: proj4string(d))),byid = TRUE)
命中< - colSums(mat)
cols< - rev(heat.colors(diff(range(hits))+ 1))
#plot
plot(d,col = cols [hits + 1] =green)
with(p,p oints(lon,lat,col =blue,pch = 19,cex = .5))
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?
解决方案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))
这篇关于如何添加一个基于位置的数据列到R中的SpatialPolygonsDataFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!