4

我想知道这是否可以做到这一点 R 。

我有一个数据作为 SpatialLinesDataFrame,另一个作为 spatialPolygonDataFrame。是否可以叠加这两个数据?

当我尝试覆盖这些时,我收到以下错误:

  jd <- overlay(res,hello) 
  Error in function (classes, fdef, mtable)  :  unable to find an inherited method for function      
  ‘overlay’ for signature ‘"SpatialLinesDataFrame", "SpatialPolygonsDataFrame"’

在上面的代码中 res 是 SpatialLinesDataFrame 而 hello 是 SpatialPolygonDataFrame。

我有一个 shapefile,然后我有 x,yand z 坐标的数据点。我想在 shapefile 上显示等高线。

我使用的过程是使用 akima 包进行插值。我用来插值的代码是

fld <- interp(x,y,z)

然后我使用以下代码将其更改为空间对象:

res <-ContourLines2SLDF(contourLines(fld))

上述命令会将等高线存储为空间数据。

然后我阅读了 shapefile 并绘制了 shapefile 和 res 如下:

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 contour stored in "res" extends beyond the shapefile. So I want to clip that contour with the shapefile and only display the contour within the shapefile area.

So I am looking for a way to clip the contour layer with the polygon layer.

I have attached the image I got with my code. enter image description here

In the image you can see the lines out of the shapefile. I also want to know how can I display the contour levels on the map.

Thank you so much.

Jdbaba

I also want to know what does overlay does exactly. Does it intersect the area of both the data ?

Thank you.

4

2 回答 2

6

It sounds like you're trying to clip your lines to the polygon extent. Use gIntersection from the rgeos package. 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")
于 2013-01-19T15:07:53.617 回答
1

Noah's answer has worked quite well for me. However, the output of his answer is a SpatialLines object, which cannot be saved as a shape file.

My two cents here is about how you can convert your SpatialLines object into a 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')
于 2015-08-02T13:49:01.293 回答