Is it possible to overlay SpatialLinesDataFrame and SpatialPolygonDataFrame
I'm wondering if it's possible to do this R.
I have one information as SpatialLinesDataFrame and the other as spatialPolygonDataFrame. Is it possible to overlay these two data?
When I try to overlay them I get the following error:
jd <- overlay(res,hello)
Error in function (classes, fdef, mtable) : unable to find an inherited method for function
βoverlayβ for signature β"SpatialLinesDataFrame", "SpatialPolygonsDataFrame"β
In the above code, res is SpatialLinesDataFrame and hello is SpatialPolygonDataFrame.
I have a shapefile and then I have data points with x, y and z coordinates. I want to show contour lines in a shapefile.
The procedure I used is using the akima package for interpolation. the code i used for interpolation is
fld <- interp(x,y,z)
Then I changed it to a feature using the following code:
res <-ContourLines2SLDF(contourLines(fld))
The above command will save the contour lines as spatial data.
Then I read the shapefile and I draw both the shapefile and res like this:
p1 <-
spplot(hello,sp.layout=list(list("sp.lines",res)),col="blue",lwd=0,fill="grey",colorkey=F)
p1
"hello" is my shapefile, and "res" is the object I created as shown above.
The problem is that the outline stored in "res" is outside the shape file. So I want to copy this path from the shapefile and only display the path in the shapefile area.
So, I'm looking for a way to copy the outline layer with a polygonal layer.
I have attached the image I received with my code.
In the image you can see the lines from the shapefile. I also want to know how I can display the contour levels on the map.
Thank you very much.
Jdbaba
I also want to know what the overlay does. Does it cross the data area?
Thank.
source to share
It looks like you are trying to anchor your lines in the polygon area. Use gIntersection
from package rgeos
. Here's a reproducible example:
library(rgeos)
xx <- SpatialPoints(coords=matrix(data=c(0,0), nrow=1))
xx <- gBuffer(spgeom=xx, width=1)
yy <- SpatialLines(list(Lines(Line(matrix(c(-1,1,-1,1), nrow=2)), ID=1)))
zz <- gIntersection(yy, xx)
You can overlay the plot like so:
plot(xx)
plot(zz, add = TRUE, col = "blue")
source to share
Noah's answer worked pretty well for me. However, the output of his response is a SpatialLines object that cannot be saved as a shape file.
My two cents here on how you can convert your SpatialLines object to SpatialLinesDataFrame and save it as a shape file.
res.df <- fortify(res) # create data frame of res, your original SpatialLinesDataFrame
data <- data.frame(id = unique(res.df$id)) # get ids of road segments
rownames(data) <- data$id
# transform SpatialLines object into SpatialLinesDataFrame
zzSpatialLineDF <- SpatialLinesDataFrame(zz, data) # convert zz object keeping road ids
# 5 Save Shape File to your working directory
writeOGR(zzSpatialLineDF, dsn = '.', layer ='zzSpatialLineDF', driver = 'ESRI Shapefile')
source to share