2015-09-14 10 views
6

Ich habe ein Polygon Shape-Datei (herunterladbare here), von dem ich enthaltend ein data.frame mit 3 Spalten erstellen möchten:Erhalten Datenrahmen mit Polygonen id und Centroid (lat long) Informationen von Shape-Datei

  1. Polygon-ID
  2. Centroid Breite
  3. Centroid Longitude

Aus dieser Antwort here, ich weiß es seine ganz einfach, diese Informationen zu erhalten, wie ein Formal Class SpatialPoints Objekt. Und wenn ich dieses Objekt in einen data.frame umwandle, verliere ich die ID-Information.

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

Irgendeine Idee, wie man die ID-Info behält?

Antwort

9
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), 
             [email protected], match.ID=FALSE) 

Es ist nur eine Frage des @data Schlitz von der ursprünglichen Shape-Datei zu bewahren dann ein SpatialPointsDataFrame aus den neuen Schwerpunkten machen.

Dann können Sie einen Datenrahmen daraus erstellen oder direkt in Plots oder anderen Spatial… Operationen verwenden.