[英]R: how to write lapply correctly to intersect polygons instead of FOR loop?
我嘗試通過raster::intersect(x,y)
將多邊形poly.list
與多邊形(SPFD) 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))
請問,我怎樣才能正確地寫一個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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.