Skip to main content

Access Ghana Census Data with R

A comprehensive guide for retrieving Ghana Statistical Service census and survey data programmatically using R and the PxWeb API. Automate data collection, build queries, and transform results for analysis.

Quick start

Get up and running with GSS StatsBank API in minutes

1

Install required packages

Install the httr2 package for HTTP requests and tidyverse for data manipulation.
install.packages("httr2")
install.packages("tidyverse")

library(httr2)
library(tidyverse)
2

Connect to the API

Set up the base URL and create a request object to interact with the GSS StatsBank API.
URL <- "https://statsbank.statsghana.gov.gh:443/api/v1/en/"
request <- request(URL)
3

Navigate to your data

Use the build_url() helper function to navigate through the database hierarchy to find your desired table.
table_req <- build_url(URL, "PHC 2021 StatsBank", "Population", "population_table.px")
The API returns available databases, topics, and tables at each level. You can explore interactively to find the data you need.
4

Retrieve and transform data

Construct a query, fetch the data, and transform it into a clean dataframe for analysis.
query_list <- list(
  query = list(
    list(
      code = "Geographic_Area",
      selection = list(filter = "all", values = list("*"))
    )
  ),
  response = list(format = "csv")
)

data <- table_req |>
  req_body_json(query_list) |>
  req_perform() |>
  resp_body_raw() |>
  readr::read_csv()

Explore by topic

Learn key concepts and master the GSS StatsBank API

PxWeb API

Understand the PxWeb technology that powers the GSS StatsBank API

Database structure

Learn how data is organized in a hierarchical folder structure

API navigation

Master the technique for navigating through databases to find tables

Build URL function

Reference guide for the helper function that simplifies navigation

Query structure

Learn how to construct JSON queries to filter and select data

Working with metadata

Discover available variables and values before querying

Step-by-step guides

Follow detailed tutorials for common tasks

Connecting to the API

Set up your R environment and establish a connection to GSS StatsBank

Navigating databases

Walk through databases, topics, and tables to find your data

Constructing queries

Build JSON queries with filters and selections

Retrieving data

Fetch data and transform it into analysis-ready dataframes

Resources

Additional references and documentation

Available databases

Browse all databases available through GSS StatsBank

PxWeb documentation

Official PxWeb API documentation and specifications

Troubleshooting

Common issues and solutions

Ready to start working with census data?

Follow our quickstart guide to retrieve your first dataset from the Ghana Statistical Service in minutes.

Get Started Now

Build docs developers (and LLMs) love