2015-09-14 11 views
6

Ho uno shapefile di poligoni (scaricabile here) da cui voglio creare un data.frame con 3 colonne che contengono:Ottenere frame di dati con i poligoni id e baricentro (lat lunga) informazioni da shapefile

  1. Poligono id
  2. latitudine Centroid
  3. Centroid Longitudine

da questa risposta here, lo so che è abbastanza facile da ottenere questa informazione come un oggetto Formal Class SpatialPoints. E quando converto questo oggetto in un data.frame, perdo le informazioni sull'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) 

Qualche idea su come mantenere le informazioni di identificazione?

risposta

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) 

E 'solo una questione di preservare la fessura @data dalla shapefile originale poi fare un SpatialPointsDataFrame dai nuovi baricentri.

Quindi è possibile creare un frame di dati da esso o utilizzarlo in grafici o altre operazioni Spatial… direttamente.

Problemi correlati