Skip to contents

This function writes a Simple Features (SF) object into a DuckDB database as a new table. The table is created in the specified schema of the DuckDB database.

Usage

ddbs_write_vector(conn, data, name, overwrite = FALSE)

Arguments

conn

a connection object to a DuckDB database

data

a sf object to write to the DuckDB database, or a local file

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.

overwrite

whether to overwrite the existing table if it exists

Value

TRUE (invisibly) for successful import

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: -85.90631 ymin: -79.44946 xmax: 151.202 ymax: 89.47244
#> Geodetic CRS:  WGS 84
#>   id crs_duckspatial                    geometry
#> 1  1       EPSG:4326 POINT (-85.90631 -51.62891)
#> 2  2       EPSG:4326  POINT (-75.58194 30.91803)
#> 3  3       EPSG:4326 POINT (-7.172937 -79.44946)
#> 4  4       EPSG:4326    POINT (151.202 89.47244)
#> 5  5       EPSG:4326 POINT (-35.74073 -63.17362)

## disconnect from db
dbDisconnect(conn)
# }