RΒΆ

R

Connect to CrateDB from R applications and notebooks.

About

The RPostgres package is the canonical C++ Interface to PostgreSQL, which is actively maintained and often preferred. An alternative is the RPostgreSQL package, written in C.

Synopsis

example.r

# Connect to CrateDB from R, using the "RPostgres: C++ Interface to PostgreSQL".
# https://cran.r-project.org/web/packages/RPostgres/

# Install the Postgres library on demand.
if (!requireNamespace("RPostgres", quietly = TRUE)) {
    install.packages("RPostgres", repos="https://cran.r-project.org")
}

# Load the DBI and Postgres libraries.
library(DBI)
library(RPostgres)

# Connect to database.
conn <- dbConnect(RPostgres::Postgres(),
                  host = "localhost",
                  port = 5432,
                  sslmode = "disable",
                  user = "crate",
                  password = "crate",
                  )
on.exit(DBI::dbDisconnect(conn), add = TRUE)

# Invoke a basic select query.
res <- dbGetQuery(conn, "SELECT * FROM sys.summits ORDER BY height DESC LIMIT 10;")
print(res)

SSL connection

Use the sslmode = "require" parameter, and replace username, password, and hostname with values matching your environment. Also use this variant to connect to CrateDB Cloud.

conn <- dbConnect(RPostgres::Postgres(),
                  host = "testcluster.cratedb.net",
                  port = 5432,
                  sslmode = "require",
                  user = "admin",
                  password = "password",
                  )

Quickstart example

Create the file example.r including the synopsis code shared above.

Start CrateDB using Docker or Podman, then invoke the example program.

docker run --rm --publish=5432:5432 docker.io/crate '-Cdiscovery.type=single-node'
Rscript example.r

Full example

Connect to CrateDB and CrateDB Cloud using R.

https://github.com/crate/cratedb-examples/tree/main/by-language/r