I'm running a for loop R that results in a shapefile being written with each iteration. The for loop runs successfully once, with a shapefile being written out, but then on the second iteration I get this error:

Error in writeOGR(temp, outfile, layer = complete_paste, driver = "ESRI Shapefile",  : 
  length(dsn) == 1L is not TRUE

For some reason, I cannot find any other question encountering this error with writeOGR(). I don't know what it means. Can anyone explain?

If it helps, here's the entire code I'm running. Basically I'm taking a large shapefile, and exporting smaller shapefiles from it by values in shp1$Vector.


shp1<- readOGR("/Users/JohnDoe/Desktop/Zone_Fixup/Z1/z1_scrub/z1_merge.shp")

output_path1<- "/Users/JohnDoe/Desktop/Zone_Fixup/Z1/z1_split/"

#Begin for loop to split shapefile by shp1$Vector values
for(i in 1:length(shp1$Vector)){

  #subset by join_id (Vector)
  temp<- shp1[shp1$Vector==shp1$Vector[i],]
  id_paste<- paste(temp$Vector)

  #Create strings for shapefile write-out
  outfile<- paste(output_path1, "Zone1_", id_paste, ".shp", sep = "")
  complete_paste<- paste("Zone1_", id_paste, sep = "")

  #Write out shapefile
  writeOGR(temp, outfile, layer = complete_paste, driver = "ESRI Shapefile", overwrite_layer = TRUE)

  • Are you expecting id_paste to return something like 'apples'? Because I'm pretty sure it must be returning c('apples', 'apples', 'apples') at least some of the time. – obrl_soil Dec 16 '18 at 23:41
  • yes but id_paste is just to inform what the file name will be in the output. No two will values will be the same so they won't overwrite each other. What does the error message mean? I don't know what's preventing the shapefile from being written out. – Wincow Dec 17 '18 at 2:06

As you've confirmed in the comments, id_paste is a vector any time temp has more than one row. This means you'd be sending multiple copies of outfile and complete_paste to writeOGR().

run paste('How do you like them ', c('apples', 'apples', 'apples'), '?', sep = '') to see what happens when you supply a vector to paste().

Try id_paste = shp1$Vector[i] instead.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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