我在R中执行point in Polygon
操作。基本上我在这里关注此示例:https://cran.r-project.org/web/packages/sp/vignettes/over.pdf
r1 = cbind(c(180114, 180553, 181127, 181477, 181294, 181007, 180409,
180162, 180114),
c(332349, 332057, 332342, 333250, 333558, 333676, 332618, 332413, 332349)
)
r2 = cbind(c(180042, 180545, 180553, 180314, 179955, 179142, 179437,
179524, 179979, 180042),
c(332373, 332026, 331426, 330889, 330683, 331133, 331623, 332152, 332357, 332373)
)
r3 = cbind(c(179110, 179907, 180433, 180712, 180752, 180329, 179875, 179668, 179572, 179269, 178879, 178600, 178544, 179046, 179110),
c(331086, 330620, 330494, 330265, 330075, 330233, 330336, 330004, 329783, 329665, 329720, 329933, 330478, 331062, 331086)
)
r4 = cbind(c(180304, 180403,179632,179420,180304),
c(332791, 333204, 333635, 333058, 332791)
)
# dummy Polygons from points
# first: Create Polygon and then Polygons object
# for Polygons object and ID is needed!
sr1 = Polygons(list(Polygon(r1)),"r1")
sr2 = Polygons(list(Polygon(r2)),"r2")
sr3 = Polygons(list(Polygon(r3)),"r3")
sr4 = Polygons(list(Polygon(r4)),"r4")
sr = SpatialPolygons(list(sr1,sr2,sr3,sr4))
plot(sr)
# dummy data, native to R
data(meuse)
# assign coordinates to data
coordinates(meuse) = ~x + y
plot(meuse)
pointsOfInterest <- over(sr, meuse)
这给了我我想要的输出,但是:我正在失去点的lng
和lat
坐标...当我执行coordinates(meuse) = ~x + y
而我执行{{{}}时会发生这种情况1}}之前和之后的数据,str
和x
的列都消失了。
答案 0 :(得分:2)
替代配方,
coordinates(meuse) = meuse[,c("x", "y")]
不会将它们从@data
插槽中移除,并导致更大的对象,因为现在重复了坐标。如果你喜欢的话可以使用它;无论如何as.data.frame(meuse)
都会放回坐标。
答案 1 :(得分:1)
给出
class(meuse)
# [1] "SpatialPointsDataFrame"
# attr(,"package")
# [1] "sp"
class(sr)
# [1] "SpatialPolygons"
# attr(,"package")
# [1] "sp"
以及?over
的帮助说:
x =&#34; SpatialPolygons&#34;,y =&#34; SpatialPoints&#34;返回多边形索引 y中的点数;如果x是SpatialPolygonsDataFrame,则是data.frame 返回x中与y对应的行。
你可以做到
(idx <- over(sr, as(meuse, "SpatialPoints")) )
# r1 r2 r3 r4
# 1 44 70 NA
meuse[na.omit(as.character(idx)), ]
# coordinates cadmium copper lead zinc elev dist om ffreq soil lime landuse dist.m
# 1 (181072, 333611) 11.7 85 299 1022 7.909 0.00135803 13.6 1 1 1 Ah 50
# 44 (180451, 332175) 1.7 22 65 176 8.694 0.21184300 NA 1 2 0 W 260
# 70 (179474, 331304) 1.8 25 81 241 7.932 0.12481000 2.9 2 2 1 Ah 160
然而,也许你想要像
这样的东西idx <- apply(rgeos::gIntersects(sr, meuse, T), 2, which)
lapply(idx, function(x) meuse[x, ])