over sp R 后的坐标

Coordinates after over sp R

我在 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)

这给了我我想要的输出,但是:我失去了点的 lnglat 坐标......当我执行 coordinates(meuse) = ~x + y 并且我做了一个前后数据的strxy的列都没有了。

给定

class(meuse)
# [1] "SpatialPointsDataFrame"
# attr(,"package")
# [1] "sp"
class(sr)
# [1] "SpatialPolygons"
# attr(,"package")
# [1] "sp"

?over 的帮助说:

x = "SpatialPolygons", y = "SpatialPoints" returns the polygon index of points in y; if x is a SpatialPolygonsDataFrame, a data.frame with rows from x corresponding to points in y is returned.

你可以

(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, ])

替代公式,

coordinates(meuse) = meuse[,c("x", "y")]

不会将它们从 @data 槽中移除,并导致更大的对象,因为坐标现在是重复的。喜欢就用; as.data.frame(meuse) 无论如何都会放回坐标。