rdflib

R-CMD-check Project Status: Active – The project has reached a stable, usable state and is being actively developed. CRAN_Status_Badge CRAN RStudio mirror downloads DOI

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "README-"
)

A friendly and consise user interface for performing common tasks on rdf data, such as parsing and converting between formats including rdfxml, turtle, nquads, ntriples, and trig, creating rdf graphs, and performing SPARQL queries. This package wraps the redland R package which provides direct bindings to the redland C library. Additionally, the package supports parsing and serialization of rdf into json-ld through the json-ld package, which binds the official json-ld javascript API. The package interface takes inspiration from the Python rdflib library.

Installation

You can install rdflib from GitHub with:

# install.packages("devtools")
devtools::install_github("ropensci/rdflib")

Basic use

While not required, rdflib is designed to play nicely with %>% pipes, so we will load the magrittr package as well:

library(magrittr)
library(rdflib)

Parse a file and serialize into a different format:

system.file("extdata/dc.rdf", package="redland") %>%
  rdf_parse() %>%
  rdf_serialize("test.nquads", "nquads")

Perform SPARQL queries:

sparql <-
 'PREFIX dc: <http://purl.org/dc/elements/1.1/>
  SELECT ?a ?c
  WHERE { ?a dc:creator ?c . }'

system.file("extdata/dc.rdf", package="redland") %>%
rdf_parse() %>%
rdf_query(sparql)

Initialize graph a new object or add triples statements to an existing graph:

x <- rdf()
x <- rdf_add(x, 
    subject="http://www.dajobe.org/",
    predicate="http://purl.org/dc/elements/1.1/language",
    object="en")
x

Change the default display format (nquads) for graph objects:

options(rdf_print_format = "jsonld")
x

JSON-LD

We can also work with the JSON-LD format through additional functions provided in the R package, jsonld.

out <- tempfile()
rdf_serialize(x, out, "jsonld")
rdf_parse(out, format = "jsonld")

For more information on the JSON-LD RDF API, see https://json-ld.org/spec/latest/json-ld-rdf/.

unlink("test.nquads")
unlink(out)
rdf_free(x)

Advanced Use

See articles from the documentation for advanced use including applications to large triplestores, example SPARQL queries, and information about additional database backends.


Citing rdflib

Please also cite the underlying redland library when citing rdflib

print(citation("rdflib"), "textVersion")
print(citation("redland"), "text")
codemeta::write_codemeta()

rofooter



ropensci/rdflib documentation built on Jan. 19, 2024, 4:57 a.m.