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

R: how to write lapply correctly to intersect polygons instead of FOR loop?

我尝试通过 raster::intersect(x,y)

将多边形列表 poly.list 与多边形 (SPFD) b 相交

我想对一堆多边形应用相同的过程,因此我编写了循环代码。然而,我的结果需要很长时间才能恢复,所以我徘徊着如何应用 *apply family 之一来让它发挥作用?

这是我的 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))

请问,我怎样才能正确地写 lapply 来做我的交集?谢谢!

这是一些虚拟数据:

# 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))