3

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

1
  • 1
    Set dsn and layer to gsub(".csv","",i). dsn will be a folder
    – mdsumner
    Sep 2, 2014 at 13:51

1 Answer 1

5

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.

1
  • Thanks, that worked. Still a lot to learn about the gdal package. At the expense of kittens, as it was a requirement. Sep 3, 2014 at 15:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.