[R-sig-Geo] Helping with write a function. Merging shape file with all fields?
Zia Ahmed
zua3 at cornell.edu
Sat Jan 23 04:45:19 CET 2010
Hi Matt:
With help of Jim Holtman (my R Guru!), I am able to modified your code
for selecting particular type of shape files from different folders
and able to combine them together. Thank you so much!
However, final polygon does not contain any filed (suppose county name,
FIPS code etc) of the shape files those I used for merging . How do I
keep these fields in my final polygon. Any idea?
Thanks
Zia
# Rode for combing Code
library(rgdal)
setwd("D:/test")
files <- list.files(pattern="soilmu_a_ny.*.shp$",
recursive=TRUE,full.names=TRUE)
# Get polygons from first file
data.first <- readOGR(files[1],gsub("^.*/(.*).shp$", "\\1", files[1]))
polygons <- slot(data.first, "polygons")
# add polygons from remaining files
for (i in 2:length(files)) {
data.temp <- readOGR(files[i], gsub("^.*/(.*).shp$", "\\1",files[i]))
polygons <- c(slot(data.temp, "polygons"),polygons)
}
# rename IDs of Polygons
for (i in 1:length(polygons)) {
slot(polygons[[i]], "ID") <- paste(i)
}
# ain't that spatial
spatialPolygons <- SpatialPolygons(polygons)
spdf <- SpatialPolygonsDataFrame(spatialPolygons,
data.frame(NewID =1:length(polygons)))
# output combined results
plot(spatialPolygons)
writeOGR(spdf, dsn="C:/test/combined.shp", layer="combined",
driver="ESRI Shapefile")
More information about the R-sig-Geo
mailing list