Skip to content
Prev 29290 / 29559 Next

Using duckdb spatial module from R (with sf)?

Hi list,

One more go at this and I'll stop for other ideas.  Below is a
slightly modified example using dbplyr::sql_render() to construct the
query, which works and to me feels a little cleaner, though maybe is
ill-advised.  Then I try to construct a spatial filter (for points in
a polygon) this way with ST_Contains, but my effort comes back empty.
Not sure where I went wrong.  Any ideas?


## boilerplate setup
library(duckdb)
conn <- DBI::dbConnect(duckdb::duckdb())
status <- DBI::dbExecute(conn, "INSTALL 'spatial';")
status <- DBI::dbExecute(conn, "LOAD 'spatial';")
test <- data.frame(site = letters[1:10], latitude = 1:10, longitude = 1:10)
DBI::dbWriteTable(conn, "test", test)

## Here we go, works!
sql <- tbl(con, "test") |>
  mutate(geom = ST_AsHEXWKB(ST_Point(longitude, latitude))) |>
  dbplyr::sql_render()
ex <- st_read(conn, query=sql, geometry_column = "geom", EWKB=FALSE)
ex

## a trivial search polygon to filter:
p2 <- rbind(c(1,1), c(1,2), c(2,2), c(1,1))
pol <-st_polygon(list(p2))
txt <- st_as_text(pol)

## Can we use this to filter duckdb?
sql <- tbl(conn, "test") |>
  mutate(geometry = ST_Point(longitude, latitude),
         geom = ST_AsHEXWKB(geometry)) |>
  filter(ST_Contains(geometry, ST_GeomFromText({txt}))) |>
  dbplyr::sql_render()
sql
ex <- st_read(conn, query=sql, geometry_column = "geom", EWKB=FALSE)
ex
## oh no! our result comes back empty?  did I need CRS on this?  Or do
I missunderstand "ST_Contains()"?

## Here's what the desired result would be from pure sf:
sf <- st_as_sf(test, coords = c(3,2))
filter <- st_as_sf(tibble(sites = "A", geometry = list(pol)))
sf |> st_filter(filter)




---
Carl Boettiger
http://carlboettiger.info/
On Tue, Aug 15, 2023 at 4:42?PM Carl Boettiger <cboettig at gmail.com> wrote: