Search code examples
rpolygonpointr-sp

Coordinates after over sp R


I perform a point in Polygon operation in R. Basically I am following this example here: 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)

That gives me my desired ouput, however: I am loosing the lng and lat coordinates of the points... That happens when I perform coordinates(meuse) = ~x + y and I do a str of the data before and after, the columns of x and y are gone.


Solution

  • Given

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

    and the help for ?over saying:

    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.

    you could do

    (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
    

    However, maybe you want something like

    idx <- apply(rgeos::gIntersects(sr, meuse, T), 2, which)
    lapply(idx, function(x) meuse[x, ])