Skip to content
Prev 26778 / 29559 Next

Spatial Query (Selection) with Apply

Hi Ariel,

It helps when asking for help with code to produce a reproducible example.
To understand your input data I've created nodes and zones based on the
spData data nz_height and nz_elev. Based on the assumption you want to find
all the nodes in each zone I think the direct answer to your question is
something like the following:

tmp2 = lapply(s, function(x) {
  nodes[zones[x, ], ]
})

The longer answer is that aggregate(), st_join() + aggregate()/summarize()
may provide quicker solutions, depending on what you want to do with the
points after grouping them by which zone they fall in.
Note: I've used sf objects based on the explanation here https://geocompr.
robinlovelace.net/spatial-operations.html#spatial-vec which may not work
with sp data but the aggregate code should work roughly the same:

# install.packages("sf")
# install.packages("spData")
library(spData)
library(sf)
#> Linking to GEOS 3.6.2, GDAL 2.2.3, proj.4 4.9.3
zones = nz
nodes = nz_height
tmp = list()
s = 1:nrow(nz)

for(i in s) {
  tmp[[i]] = nodes[nz[i, ], ]
}

# understand what's going on with plots (not shown)
# plot(st_geometry(nz))
# plot(st_geometry(tmp[[i]]), add = TRUE, col = "red")
# plot(nz[i, ], col = "green", add = TRUE)

tmp2 = lapply(s, function(x) {
  nz_height[nz[x, ], ]
})

identical(tmp, tmp2)
#> [1] TRUE

Created on 2018-08-27 by the [reprex package](http://reprex.tidyverse.org)
(v0.2.0).

I've also pasted the reprex into the geocompr github tracker so the plots
can be seen and the code formatted: https://github.com/
Robinlovelace/geocompr/issues/294

Hope this helps,

Robin


On Mon, Aug 27, 2018 at 9:53 PM, Ariel Fuentesdi <ariel.fuentesdi at usach.cl>
wrote: