R:如何正确编写 lapply 以相交多边形而不是 FOR 循环



我尝试将多边形列表与多边形 (SPFD) poly.list b相交raster::intersect(x,y)

我想对一堆多边形应用相同的过程,因此我编写了循环代码。但是,需要很长时间才能获得我的结果,所以我徘徊如何应用*应用家庭之一以使其工作?

这是我的 for 循环:

int.list<-list()
for (i in 1:length(Poly.list.bb.from06)) {
  my.int<-intersect(poly.list[[i]], b)
  int.list[[i]]<-my.int
}

这是我的 lapply 函数(因为我想在多个多边形列表上应用intersect并获取多边形列表)

int.list<-lapply(poly.list, intersect(poly.list, b))
int.list<-lapply(poly.list, function(x) intersect(poly.list, b))

请问,我怎样才能正确地写出我的交叉点?谢谢!

以下是一些虚拟数据:

# stack overflow
library(rgeos)
# create polygon
p1 = readWKT("POLYGON((2 2,-2 2,-2 -2,2 -2,2 2))")
# create two buffers - one wth {raster}, one with {rgeos},
# both covers also original polygon !
p2<-readWKT("POLYGON((1.5 1.5,-1.5 1.5,-1.5 -1.5,1.5 -1.5,1.5 1.5))")
poly.list<-list(p1, p2)
b = readWKT("POLYGON((1 1,-1 1,-1 -1,1 -1,1 1))")
gIntersects()

您要查找的函数:

sapply(poly.list, function(x) gIntersects(x, b))
[1] TRUE TRUE

根据@HubertL答案,这个是我正在寻找的答案......

int.list2<-lapply(poly.list, function(x) intersect(x, b))

整个代码:

# stack overflow
library(rgeos)
# create polygon
p1 = readWKT("POLYGON((2 2,-2 2,-2 -2,2 -2,2 2))")
# create two buffers - one wth {raster}, one with {rgeos},
# both covers also original polygon !
p2<-readWKT("POLYGON((1.5 1.5,-1.5 1.5,-1.5 -1.5,1.5 -1.5,1.5 1.5))")
poly.list<-list(p1, p2)
b = readWKT("POLYGON((1 1,-1 1,-1 -1,1 -1,1 1))")
# intersect list of polygons with a polygon,
# get back list of polygons
int.list2<-lapply(poly.list, function(x) intersect(x, b))

最新更新