1

This question has been asked before, but I find the answer confusing since there are no reproducible examples that link the question and the answer, and the answer doesn't actually use the writeOGR function. Use lapply and writeOGR to write multiple shapefiles within a list

I have a list of spatial objects. I want to export all of the using writeOGR. How can I apply this function to the list of spatial objects?

The solution I've come up with applies writeOGR to the outer list element, and I suppose I need to apply it to the inner list element, but I don't know how to do this.

library(GISTools)
library(rgdal)
data(tornados)

torn_list <- list(torn, torn2)
lapply(torn_list, function(x) writeOGR(obj = x, dsn = "tempdir", layer = x, driver = "ESRI Shapefile"))

Error in as.character.default(layer) : 
  no method for coercing this S4 class to a vector

Any suggestions?


To clarify, I do want to do this to a list of shape files that have different coordinate reference systems. I would like to create a different shapefile for every element of the list. I realize now I would need to have some way of making the "layer =" argument for each element of this list as well.

2 Answers 2

3

you are trying to assign the spatial object itself as the name for the shapefile produced (the layer argument). Below an example that works for me

lapply(torn_list, function(x) writeOGR(obj = x, dsn = "tempdir", layer = as.character(round(runif(1,0,100),0)), driver = "ESRI Shapefile"))

the output will be shapefiles with random numbers. if you want the shapefiles to be named "torn" and "torned2", you will need to play with the layer argument so that lapply yields it in each of its "iterations"

1

A shapefile can only have one layer, and a layer has to have the same geometry type and the same columns, and the same coordinate system.

If all those conditions are true, you can use rbind to make a larger spatial data frame and write that with writeOGR.

torn and torn2 have different coordinate systems so you can't do this.

You can write multiple layers to a geopackage file. But no, not a shapefile.

1
  • I've added some clarification to my question in response to your answer. Mar 30, 2020 at 20:52

Your Answer

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

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