[GIS] Writing SpatialLines objects in R

mapsrshapefile

I used the function landgenreport from the package popgenreport in R to create an object result.

This object is a list with various objects including SpatialLines class objects. I am trying to write these lines to a file readable in GIS software such as ArcGIS or QGIS. The problem is that I can not find a way to do that. I've tried several functions from several packages and I always get an error.

library(raster)
library(rgdal)
library(sp)
library(maptools)  

results$leastcost$paths[[1]][[78]] #this is the specific SpatialLine
linha78<-results$leastcost$paths[[1]][[78]]
writeSpatialShape(linha78,"linha78.shp")
Error in writeSpatialShape(results$leastcost$paths[[1]][[78]],"linha78.shp"):x is aSpatialLinesobject, not a compatible Spatial*DataFrame

So I tried to transform the SpatialLines object to a SpatialDataFrame and got another error message.

x = data.frame(linha78)
Error in as.data.frame.default(x[[i]], optional = TRUE) : 
cannot coerce class "structure("SpatialLines", package = "sp")" to a data.frame

I've tried a lot a different possible solutions I read here and there, but it simply does not work. As such:

writeOGR with a spatialpolygon simplified by gSimplify

How to export a dataset with "SpatialPolygonsDataFrame" as a shapefile

http://r-sig-geo.2731867.n2.nabble.com/Saving-a-spatial-point-object-into-a-shapefile-td5704759.html

Best Answer

If you're using maptools it says not to specify the extension ".shp"

Try:

results$leastcost$paths[[1]][[78]] #this is the line
linha78<-results$leastcost$paths[[1]][[78]]
writeSpatialShape(linha78,"linha78")

Update: You need to create a SpatialLinesDataFrame in order to write it out. In the OP you just created a data.frame (not spatial). id=1:length creates data.frame that has rows 1 to the length of your linha78. Try typing length(linha78 into the console, it should give you the number of rows for linha78 :

results$leastcost$paths[[1]][[78]] #this is the line
linha78<-results$leastcost$paths[[1]][[78]]
df<-SpatialLinesDataFrame(linha78, data.frame(id=1:length(linha78)))
writeOGR(df, dsn="c:/Ouputs" ,layer="linha78",driver="ESRI Shapefile")
Related Question