knitr::opts_chunk$set(echo = TRUE)
# install.packages("printr", type = "source", repos = c("https://yihui.name/xran", CRAN = "https://cran.rstudio.com"))
library(printr)

Project Status: Active – The project has reached a stable, usable state and is being actively developed. CRAN_Status_Badge CRAN Total Downloads License: MIT

This is an R wrapper for the Wikidata Query Service (WDQS) which provides a way for tools to query Wikidata via SPARQL (see the beta at https://query.wikidata.org/). It is written in and for R, and was inspired by Os Keyes' WikipediR and WikidataR packages.

Author: Mikhail Popov (Wikimedia Foundation)
License: MIT
Status: Active

Installation

install.packages("WikidataQueryServiceR")

To install the development version:

# install.packages("remotes")
remotes::install_github("wikimedia/WikidataQueryServiceR@main")

Usage

library(WikidataQueryServiceR)

You submit SPARQL queries using the query_wikidata() function.

Example: fetching genres of a particular movie

In this example, we find an "instance of" (P31) "film" (Q11424) that has the label "The Cabin in the Woods" (Q45394), get its genres (P136), and then use WDQS label service to return the genre labels.

query_wikidata('SELECT DISTINCT
  ?genre ?genreLabel
WHERE {
  ?film wdt:P31 wd:Q11424.
  ?film rdfs:label "The Cabin in the Woods"@en.
  ?film wdt:P136 ?genre.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}')

For more example SPARQL queries, see this page on Wikidata.

query_wikidata() can accept multiple queries, returning a (potentially named) list of data frames. If the vector of SPARQL queries is named, the results will inherit those names.

Fetching queries from Wikidata's examples page

The package provides a WikipediR-based function for getting SPARQL queries from the WDQS examples page.

sparql_query <- get_example(c("Cats", "How many states this US state borders"))
sparql_query[["How many states this US state borders"]]
cat("```SPARQL\n", sparql_query[["How many states this US state borders"]], "\n```")

Now we can run all extracted SPARQL queries:

results <- query_wikidata(sparql_query)
lapply(results, dim)
head(results$`How many states this US state borders`)

Links for learning SPARQL

Additional Information

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.



bearloga/WikidataQueryServiceR documentation built on Aug. 1, 2020, 7:37 p.m.