I have a shapefile of 50 polygons. I've read it into R. Now I want to use R to export 50 shapefiles, one for each polygon. This seems like an intuitive application of apply. But I'm having a devil of a time doing it.
I tried a for loop (like Splitting vector layer in R).
STNCODES <- unique(ptsbuf_400@data$STNCODE)
for (i in 1:length(STNCODES)) {
tmp <- data[ptsbuf_400@data$STNCODE == STNCODES[i], ]
writeOGR(tmp, dsn=getwd(), STNCODES[i], driver="ESRI Shapefile",
overwrite_layer=TRUE)
}
I get the following error:
Error in data[ptsbuf_400@data$STNCODE == STNCODES[i], ] : object of type 'closure' is not subsettable
This seems to be the cause of the error, but I'm at a loss how to fix it:
data[ptsbuf_400@data$STNCODE == STNCODES[i], ]
Amtrak station data here
Example using SF works--likely there is some difference between the spatial object generated by readOGR/writeOGR and read_sf and write_sf--the latter seems to be a vector, while the sp object is not?