我有一个多边形shapefile(可在这里下载),我想从中创建一个data.frame包含3列的3列:
从这个答案在这里,我知道它很容易得到这个信息作为Formal Class SpatialPoints对象.当我将此对象转换为data.frame时,我会丢失id信息.
# Load Shapefile
Legislative_areas <- readOGR(dsn = 'C:/Users/.../Downloads/Legislative2010UTM', layer ='Legislative2010UTM')
# Get centroids
cent <- gCentroid(Legislative_areas, byid=TRUE)
# Convert to data.frame, but loose id info
cent <- as.data.frame(cent)
Run Code Online (Sandbox Code Playgroud)
关于如何保存身份信息的任何想法?
hrb*_*str 12
library(rgdal)
library(rgeos)
# download w/o wasting bandwidth
URL <- "ftp://dnrftp.dnr.ne.gov/pub/data/state/Legislative2010UTM.zip"
fil <- basename(URL)
if (!file.exists(fil)) download.file(URL, fil)
# unzip & get list of files
fils <- unzip(fil)
# find the shapefile in it
shp <- grep("shp$", fils, value=TRUE)
# get the first layer from it
lay <- ogrListLayers(shp)[1]
# read in the shapefile
leg <- readOGR(shp, lay)
# get the centroids and then convert them to a SpatialPointsDataFrame
leg_centers <- SpatialPointsDataFrame(gCentroid(leg, byid=TRUE),
leg@data, match.ID=FALSE)
Run Code Online (Sandbox Code Playgroud)
这只是保留@data原始shapefile中的插槽然后制作一个SpatialPointsDataFrame从新的质心中创建的问题.
然后,您可以从中创建数据框或Spatial…直接在绘图或其他操作中使用它.