I'm working with duckdb in R and would like to insert a record using dplyr
. I have included an example below of what I'm trying to achieve.
First, I load my libraries, create a toy dataset, then load it into a database.
# Load libraries
library(DBI)
library(duckdb)
library(dplyr)
# Create database connection
con <- dbConnect(duckdb(),
dbdir="test.duckdb",
read_only=FALSE)
# Toy data frame
df <- data.frame(a = 1:5,
b = letters[1:5],
c = runif(5))
# Write data to table
dbWriteTable(con, "foo", df)
I can now query my database using both SQL and dplyr
syntax:
# Query
dbGetQuery(con, "SELECT * FROM foo")
# a b c
# 1 1 a 0.1407891
# 2 2 b 0.8824569
# 3 3 c 0.2863700
# 4 4 d 0.9010191
# 5 5 e 0.8676229
tbl(con, "foo") %>% collect
# # A tibble: 5 x 3
# a b c
# <int> <chr> <dbl>
# 1 1 a 0.141
# 2 2 b 0.882
# 3 3 c 0.286
# 4 4 d 0.901
# 5 5 e 0.868
And I can insert a record with SQL syntax:
# Insert with SQL
dbExecute(con,
"INSERT INTO foo VALUES (?, ?, ?)",
list(6, "F", 0.5))
dbGetQuery(con, "SELECT * FROM foo")
# a b c
# 1 1 a 0.1407891
# 2 2 b 0.8824569
# 3 3 c 0.2863700
# 4 4 d 0.9010191
# 5 5 e 0.8676229
# 6 6 F 0.5000000
Fantastic!
My question is, how do I write the SQL insert statement but using dplyr
syntax instead?