Skip to contents

Retrieves the data from a DuckDB table with a geometry column, and convert it to an R sf object.

Usage

ddbs_read_vector(conn, name, crs = NULL, crs_column = "crs_duckspatial")

Arguments

conn

a connection object to a DuckDB database

name

a character string of length one specifying the name of the table, or a character string of length two specifying the schema and table names.

crs

the coordinates reference system of the data. Specify if the data doesn't have crs_column, and you know the crs

crs_column

a character string of length one specifying the column storing the CRS (created automatically by ddbs_write_vector). Set to NULL if absent

Value

an sf object

Examples

# \donttest{
## load packages
library(duckdb)
library(duckspatial)
library(sf)

## connect to in memory database
conn <- dbConnect(duckdb::duckdb())

## install the spatial exntesion
ddbs_install(conn)
#>  spatial extension version <2905968> is already installed in this database
ddbs_load(conn)
#>  Spatial extension loaded

## create random points
random_points <- data.frame(
  id = 1:5,
  x = runif(5, min = -180, max = 180),  # Random longitude values
  y = runif(5, min = -90, max = 90)     # Random latitude values
)

## convert to sf
sf_points <- st_as_sf(random_points, coords = c("x", "y"), crs = 4326)

## insert data into the database
ddbs_write_vector(conn, sf_points, "points")
#>  Table points successfully imported

## read data back into R
ddbs_read_vector(conn, "points", crs = 4326)
#>  Table points successfully imported.
#> Simple feature collection with 5 features and 2 fields
#> Geometry type: POINT
#> Dimension:     XY
#> Bounding box:  xmin: -111.0535 ymin: -39.85251 xmax: 161.195 ymax: 8.028611
#> Geodetic CRS:  WGS 84
#>   id crs_duckspatial                    geometry
#> 1  1       EPSG:4326   POINT (25.21618 7.646474)
#> 2  2       EPSG:4326  POINT (-59.14113 8.028611)
#> 3  3       EPSG:4326   POINT (34.6546 -39.85251)
#> 4  4       EPSG:4326 POINT (-111.0535 -9.593556)
#> 5  5       EPSG:4326   POINT (161.195 -23.12799)

## disconnect from db
dbDisconnect(conn)
# }