我有两个数据框:
points
包含一系列带x, y
坐标的点。poly
包含两个多边形的坐标(我实际上有 100 多个,但在这里保持简单)。我希望能够向数据框中添加points
一个名为的额外列Area
,其中包含点所在多边形的名称。
poly <- data.frame(
pol= c("P1", "P1","P1","P1","P1","P2","P2","P2","P2", "P2"),
x=c(4360, 7273, 7759, 4440, 4360, 8720,11959, 11440,8200, 8720),
y=c(1009, 9900,28559,28430,1009,9870,9740,28500,28040,9870))
points <- data.frame(
object = c("P1", "P1","P1","P2","P2","P2"),
timestamp= c(1485670023468,1485670023970, 1485670024565, 1485670025756,1485670045062, 1485670047366),
x=c(6000, 6000, 6050, 10000, 10300, 8000),
y=c(10000, 20000,2000,5000,20000,2000))
plot(poly$x, poly$y, type = 'l')
text(points$x, points$y, labels=points$object )
所以基本上在这个例子中,前 2 行应该有,Area= "P1"
而最后一个点应该是空白的,因为该点不包含在任何多边形中。
我曾尝试使用该函数,in.out
但无法按照我的描述构建数据框。
非常感谢任何帮助!
尽管这是使用for
循环,但实际上速度相当快。
library(mgcv)
x <- split(poly$x, poly$pol)
y <- split(poly$y, poly$pol)
todo <- 1:nrow(points)
Area <- rep.int("", nrow(points))
pol <- names(x)
# loop through polygons
for (i in 1:length(x)) {
# the vertices of i-th polygon
bnd <- cbind(x[[i]], y[[i]])
# points to allocate
xy <- with(points, cbind(x[todo], y[todo]))
inbnd <- in.out(bnd, xy)
# allocation
Area[todo[inbnd]] <- pol[i]
# update 'todo'
todo <- todo[!inbnd]
}
points$Area <- Area
其效率的两个原因:
for
循环是通过多边形,而不是点。所以如果你有 100 个多边形和 100000 个点要分配,循环只有 100 次迭代而不是 100000。在每次迭代中,in.out
利用C 函数的矢量化能力;todo
变量控制通过循环分配的点数。随着它的发展,工作集正在减少。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句