Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writeOGR saving for multiple shapefiles

I'd like to use writeOGR inside a loop to save shapefiles to folders. I'm having trouble figuring out how the name is used to save the actual file.

Say you've got this code:

require(sp)
require(rgdal)

for (i in listafiles){
ffile <-read.csv(i)    #reads file
###do some stuff on the file and obtain a polygon sp_poly

sp_poly <- SpatialPolygons(list(Polygons(list(Polygon(coords)), ID=1)))
sp_poly_df <- SpatialPolygonsDataFrame(sp_poly, data=data.frame(ID=1))
##here comes the problem
writeOGR(sp_poly_df, dsn, layer, driver="ESRI Shapefile")

}

I'd like writeOGR to save each resulting shapefile in a separate folder, with the name of the file. E.g., when 'i' is 'school17.csv', writeOGR would create subfolder .\school17\ and the 3 shapefiles be named: (school17.dbf | school17.shp | school17.shx)

I can't figure out how the dsn and layer parameters work.

Thanks in advance, dev

like image 439
user3310782 Avatar asked Feb 03 '26 14:02

user3310782


1 Answers

Just set dsn and layer to the name you have:

{
  ### ... we are in the loop
  dsn <- layer <- gsub(".csv","",i)
  writeOGR(sp_poly_df, dsn, layer, driver="ESRI Shapefile")
}
## E.g. 
list.files()
## [1] "a" "b" "c"
list.files(list.files()[1])
##[1] "a.dbf" "a.prj" "a.shp" "a.shx"

But remember, every time you create a 'shapefile', kittens die.

like image 59
mdsumner Avatar answered Feb 05 '26 03:02

mdsumner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!