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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With