A curated list of open technology projects to sustain a stable climate, energy supply, biodiversity and natural resources.

Geocomputation with R

A book on geographic data analysis, visualization and modeling with R.
https://github.com/geocompx/geocompr

Category: Sustainable Development
Sub Category: Education

Keywords

book course education gdal geo geocomputation geocompx geography geos geospatial geospatial-data mapping-tools maps postgis r raster rspatial rstats simple-features spatial

Keywords from Contributors

proj routes cycle spatial-analysis visualisation spatial-data unconf web-mapping tidy-data transportation

Last synced: about 3 hours ago
JSON representation

Repository metadata

Geocomputation with R: an open source book

README.Rmd

          ---
output: github_document
---



```{r, echo = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "images/"
)
is_online = curl::has_internet()
```

# Geocomputation with R  


[![Binder](http://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/geocompx/geocompr/main?urlpath=rstudio)
[![RstudioCloud](images/cloud.png)](https://rstudio.cloud/project/1642300)
[![Actions](https://github.com/geocompx/geocompr/workflows/Render/badge.svg)](https://github.com/geocompx/geocompr/actions)
[![Docker](https://img.shields.io/docker/pulls/geocompr/geocompr?style=plastic)](https://github.com/geocompx/docker/)
[![discord](https://img.shields.io/discord/878051191374876683?label=discord&logo=Discord&color=blue)](https://discord.com/invite/PMztXYgNxp)
[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://github.com/codespaces/new?hide_repo_select=true&ref=main&repo=84222786&machine=basicLinux32gb&devcontainer_path=.devcontainer.json&location=WestEurope)



## Introduction

This repository hosts the code underlying Geocomputation with R, a book by [Robin Lovelace](https://www.robinlovelace.net/), [Jakub Nowosad](https://jakubnowosad.com/), and [Jannes Muenchow](https://github.com/jannes-m).
If you find the contents useful, please [cite it](https://github.com/geocompx/geocompr/raw/main/CITATION.bib) as follows:

> Lovelace, Robin, Jakub Nowosad and Jannes Muenchow (2025). Geocomputation with R. The R Series. CRC Press.

To learn more about the second edition of the book, see the ["Second edition of Geocomputation with R is complete" blog post](https://geocompx.org/post/2024/geocompr2-bp3/).

The first version of the book has been published by [CRC Press](https://www.crcpress.com/9781138304512) in the [R Series](https://www.routledge.com/Chapman--HallCRC-The-R-Series/book-series/CRCTHERSER) and can be viewed online at [bookdown.org](https://bookdown.org/robinlovelace/geocompr/).
Read the latest version at [r.geocompx.org](https://r.geocompx.org/).







Contributions are very welcome.

## Contributing

We encourage contributions on any part of the book, including:

- improvements to the text, e.g., clarifying unclear sentences, fixing typos (see guidance from [Yihui Xie](https://yihui.org/en/2013/06/fix-typo-in-documentation/));
- changes to the code, e.g., to do things in a more efficient way; 
- suggestions on content (see the project's [issue tracker](https://github.com/geocompx/geocompr/issues));
- improvements to and alternative approaches in the Geocompr solutions booklet hosted at [r.geocompx.org/solutions](https://r.geocompx.org/solutions) (see a blog post on how to update solutions in files such as [_01-ex.Rmd](https://github.com/geocompx/geocompr/blob/main/_01-ex.Rmd) [here](https://geocompx.org/post/2022/geocompr-solutions/))

See [our-style.md](https://github.com/geocompx/geocompr/blob/main/misc/our-style.md) for the book's style.

```{r contributors, include=FALSE}
contributors = source("code/list-contributors.R")[[1]]
# save for future reference:
readr::write_csv(contributors, "extdata/contributors.csv")
# table view:
# knitr::kable(contributors, caption = "Contributors to Geocomputation with R")
# text view
c_txt = contributors$name
c_url = contributors$link
c_rmd = paste0("[", c_txt, "](", c_url, ")")
contributors_text = paste0(c_rmd, collapse = ", ")
```

Many thanks to all contributors to the book so far via GitHub (this list will update automatically): `r contributors_text`.

During the project we aim to contribute 'upstream' to the packages that make geocomputation with R possible.
This impact is recorded in [`our-impact.csv`](https://github.com/geocompx/geocompr/blob/main/misc/our-impact.csv).

## Downloading the source code

The recommended way to get the source code underlying Geocomputation with R on your computer is by cloning the repo.
You can can that on any computer with [Git](https://github.com/git-guides/install-git) installed with the following command:

```bash
git clone https://github.com/geocompx/geocompr.git
```

An alternative approach, which we recommend for people who want to contribute to open source projects hosted on GitHub, is to install the [`gh` CLI tool](https://github.com/cli/cli#installation).
From there cloning a fork of the source code, that you can change and share (including with Pull Requests to improve the book), can be done with the following command:

```bash
gh repo fork geocompx/geocompr # (gh repo clone geocompx/geocompr # also works)
```

Both of those methods require you to have Git installed.
If not, you can download the book's source code from the URL https://github.com/geocompx/geocompr/archive/refs/heads/main.zip .
Download/unzip the source code from the R command line to increase reproducibility and reduce time spent clicking around:

```{r dl-unzip}
#| eval=FALSE
u = "https://github.com/geocompx/geocompr/archive/refs/heads/main.zip"
f = basename(u)
download.file(u, f)        # download the file
unzip(f)                   # unzip it
file.rename(f, "geocompr") # rename the directory
rstudioapi::openProject("geococompr") # or open the folder in vscode / other IDE
```

## Reproducing the book in R/RStudio/VS Code

To ease reproducibility, we created the `geocompkg` package.
Install it with the following commands:

```{r readme-install-github}
#| eval=FALSE
install.packages("remotes")
# To reproduce the first Part (chapters 1 to 8):
install.packages("geocompkg", repos = c("https://geocompr.r-universe.dev", "https://cloud.r-project.org"), dependencies = TRUE, force = TRUE)
```

Installing `geocompkg` will also install core packages required for reproducing **Part I of the book** (chapters 1 to 8). 
Note: you may also need to install [system dependencies](https://github.com/r-spatial/sf#installing) if you're running Linux (recommended) or Mac operating systems.
You also need to have the [**remotes**](https://github.com/r-lib/remotes/) package installed:

To reproduce book **in its entirety**, run the following command (which installs additional 'Suggests' packages, this may take some time to run!):

```{r readme-install-github-2, message=FALSE, results='hide'}
#| eval=FALSE
# Install packages to fully reproduce book (may take several minutes):
options(repos = c(
  geocompx = "https://geocompx.r-universe.dev",
  cran = "https://cloud.r-project.org/"
))
# From geocompx.r-universe.dev (recommended):
install.packages("geocompkg", dependencies = TRUE)

# Alternatively from GitHub:
remotes::install_github("geocompx/geocompkg", dependencies = TRUE)
```

You need a recent version of the GDAL, GEOS, PROJ and udunits libraries installed for this to work on Mac and Linux.
See the **sf** package's [README](https://github.com/r-spatial/sf) for information on that.
After the dependencies have been installed you should be able to build and view a local version the book with:

```{r readme-render-book}
#| eval=FALSE
# Change this depending on where you have the book code stored:
rstudioapi::openProject("~/Downloads/geocompr")
 # or code /location/of/geocompr in the system terminal
 # or cd /location/of/geocompr then R in the system terminal, then:
bookdown::render_book("index.Rmd") # to build the book
browseURL("_book/index.html")      # to view it
# Or, to serve a live preview the book and observe impact of changes:
bookdown::serve_book(".")
```





```{r gen-code, results='hide', echo=FALSE}
#| eval=FALSE
geocompkg:::generate_chapter_code()
```

## Geocompr in a devcontainer

A great feature of VS Code is [devcontainers](https://code.visualstudio.com/docs/remote/containers), which allow you to develop in an isolated Docker container.
If you have VS Code and the necessary dependencies installed on your computer, you can build Geocomputation with R in a devcontainer as shown below (see [#873](https://github.com/geocompx/geocompr/issues/873) for details):

![](https://user-images.githubusercontent.com/1825120/193398022-bbcfbfda-5d57-4c57-8db3-ed1fdb4a07be.png)

## Geocompr in Binder

For many people the quickest way to get started with Geocomputation with R is in your web browser via Binder.
To see an interactive RStudio Server instance click on the following button, which will open [mybinder.org](https://mybinder.org/v2/gh/geocompx/geocompr/main?urlpath=rstudio) with an R installation that has all the dependencies needed to reproduce the book:

[![Launch Rstudio Binder](http://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/geocompx/geocompr/main?urlpath=rstudio)

You can also have a play with the repository in RStudio Cloud by clicking on this link (requires log-in):

[![Launch Rstudio Cloud](images/cloud.png)](https://rstudio.cloud/project/1642300)

## Geocomputation with R in a Docker container

See the [geocompx/docker](https://github.com/geocompx/docker) repository for details.

## Reproducing this README

To reduce the book's dependencies, scripts to be run infrequently to generate input for the book are run on creation of this README.

The additional packages required for this can be installed as follows:

```{r extra-pkgs, message=FALSE, eval=FALSE}
source("code/extra-pkgs.R")
```

With these additional dependencies installed, you should be able to run the following scripts, which create content for the book, that we've removed from the main book build to reduce package dependencies and the book's build time:

```{r source-readme, eval=FALSE}
source("code/01-cranlogs.R")
source("code/sf-revdep.R")
source("code/09-urban-animation.R")
source("code/09-map-pkgs.R")
```

Note: the `.Rproj` file is configured to build a website not a single page.
To reproduce this [README](https://github.com/geocompx/geocompr/blob/main/README.Rmd) use the following command:

```{r render-book, eval=FALSE}
rmarkdown::render("README.Rmd", output_format = "github_document", output_file = "README.md")
```


```{r scripts,  eval=FALSE, echo=FALSE}
# We aim to make every script in the `code` folder reproducible.
# To check they can all be reproduced run the following:
# Aim: test reproducibility of scripts
script_names = list.files("code", full.names = T)
avoid = "pkgs|anim|us|saga|sliver|tsp|parti|polycent|cv|svm|data|location|eco|rf|cran|hex"
dontrun = grepl(avoid, script_names)
script_names = script_names[!dontrun]
counter = 0
for(i in script_names[45:length(script_names)]) {
  counter = counter + 1
  print(paste0("Script number ", counter, ": ", i))
  source(i)
}
```






```{r gen-stats, echo=FALSE, message=FALSE, warning=FALSE, eval=FALSE}
# source("code/generate-chapter-code.R")
book_stats = readr::read_csv("extdata/word-count-time.csv",
                             col_types = ("iiDd"))

# to prevent excessive chapter count
if (Sys.Date() > max(book_stats$date) + 5) {
  book_stats_new = geocompkg:::generate_book_stats()
  book_stats = bind_rows(book_stats, book_stats_new)
  readr::write_csv(book_stats, "extdata/word-count-time.csv")
}
book_stats = dplyr::filter(book_stats, chapter <= 15) 
library(ggplot2)
book_stats$chapter = formatC(book_stats$chapter, width = 2, format = "d", flag = "0")
book_stats$chapter = fct_rev(as.factor(book_stats$chapter))
book_stats$n_pages = book_stats$n_words / 300
```

```{r bookstats, warning=FALSE, echo=FALSE, fig.width=8, fig.height=5, eval=FALSE}
ggplot(book_stats) +
  geom_area(aes(date, n_pages, fill = chapter), position = "stack") +
  ylab("Estimated number of pages") +
  xlab("Date") + 
  scale_x_date(date_breaks = "2 month",
               limits = c(min(book_stats$date), as.Date("2018-10-01")),
               date_labels = "%b %Y") +
  coord_cartesian(ylim = c(0, 350))
```



## Citations

The main packages used in this book are cited from `packages.bib`.
Other citations are stored online using Zotero.

If you would like to add to the references, please use Zotero, join the [open group](https://www.zotero.org/groups/418217/energy-and-transport) add your citation to the open [geocompr library](https://www.zotero.org/groups/418217/energy-and-transport/items/collectionKey/9K6FRP6N).

We use the following citation key format:

```
[auth:lower]_[veryshorttitle:lower]_[year]
```

This can be set from inside Zotero desktop with the Better Bibtex plugin installed (see [github.com/retorquere/zotero-better-bibtex](https://github.com/retorquere/zotero-better-bibtex)) by selecting the following menu options (with the shortcut `Alt+E` followed by `N`), and as illustrated in the figure below:

```
Edit > Preferences > Better Bibtex
```

![](images/zotero-settings.png)

Zotero settings: these are useful if you want to add references.

When you export the citations as a .bib file from Zotero, use the  `Better BibTex` (not `BibLaTeX`) format.

We use Zotero because it is a powerful open source reference manager that integrates well with citation tools in VS Code and RStudio.


        

Citation (CITATION.bib)

@book{lovelace_geocomputation_2025,
  title = {Geocomputation with {{R}}},
  isbn = {9781032248882},
  edition = {Second},
  abstract = {Book on geographic data with R.},
  publisher = {{CRC Press}},
  author = {Lovelace, Robin and Nowosad, Jakub and Muenchow, Jannes},
  year = {2025}
}


Owner metadata


GitHub Events

Total
Last Year

Committers metadata

Last synced: 6 days ago

Total Commits: 8,588
Total Committers: 91
Avg Commits per committer: 94.374
Development Distribution Score (DDS): 0.598

Commits in past year: 282
Committers in past year: 9
Avg Commits per committer in past year: 31.333
Development Distribution Score (DDS) in past year: 0.56

Name Email Commits
jn t****i@g****m 3455
Robin Lovelace r****x@g****m 3385
jannes-m m****a@g****e 1317
jannes j****s@c****m 83
Marie-Helene Burle m****2@s****a 50
Andrew Black 1****s 41
florisvdh f****e@i****e 38
babayoshihiko b****o@m****m 29
katygregg 3****g 19
Lawrence V l****e@v****t 10
jannes.muenchow j****w@g****m 8
Roger Bivand R****d@n****o 8
Ivan Dubrovin i****n@i****m 8
Kiran k****1@g****m 7
Cui Xueqin x****i@g****m 6
Olivier Leroy l****i@g****m 6
Steve Kerr 5****r 5
Zeb Burke-Conte z****c 5
marcosci s****o@g****m 4
Erin Stearns e****8@g****m 4
FlorentBedecarratsNM 7****M 4
dcooley d****1@g****m 4
krystof236 6****6 3
eyesofbambi g****g@l****k 3
Nick Bearman n****k@g****k 3
MikeJohnPage 3****e 3
Marius Appel m****l@u****e 3
Darrell Carvalho 5****o 3
Edzer Pebesma e****a@u****e 2
pat-s p****z@g****m 2
and 61 more...

Committer domains:


Issue and Pull Request metadata

Last synced: 1 day ago

Total issues: 116
Total pull requests: 164
Average time to close issues: 4 months
Average time to close pull requests: 21 days
Total issue authors: 29
Total pull request authors: 19
Average comments per issue: 3.93
Average comments per pull request: 1.45
Merged pull request: 152
Bot issues: 0
Bot pull requests: 0

Past year issues: 26
Past year pull requests: 40
Past year average time to close issues: 4 days
Past year average time to close pull requests: about 17 hours
Past year issue authors: 8
Past year pull request authors: 10
Past year average comments per issue: 2.96
Past year average comments per pull request: 1.43
Past year merged pull request: 36
Past year bot issues: 0
Past year bot pull requests: 0

More stats: https://issues.ecosyste.ms/repositories/lookup?url=https://github.com/geocompx/geocompr

Top Issue Authors

  • Robinlovelace (58)
  • Nowosad (16)
  • tibbles-and-tribbles (9)
  • cc50liu (5)
  • biscotty666 (2)
  • babayoshihiko (2)
  • Lvulis (2)
  • dhersz (1)
  • sy5938 (1)
  • rriem (1)
  • Aditya-Dahiya (1)
  • BlaiseKelly (1)
  • selvaje (1)
  • ejokujona (1)
  • maltenform (1)

Top Pull Request Authors

  • Robinlovelace (49)
  • tibbles-and-tribbles (43)
  • babayoshihiko (20)
  • Nowosad (16)
  • jannes-m (10)
  • smkerr (5)
  • eblondel (4)
  • florisvdh (4)
  • howardbaek (2)
  • edzer (2)
  • BjnNowak (1)
  • jacobvjk (1)
  • ahmohil (1)
  • Aditya-Dahiya (1)
  • jkennedyie (1)

Top Issue Labels

  • help wanted (6)
  • good first issue (4)
  • question (2)
  • enhancement (1)

Top Pull Request Labels


Dependencies

.binder/Dockerfile docker
  • geocompr/geocompr binder build
Dockerfile docker
  • geocompr/geocompr latest build
.github/workflows/dev-sf.yaml actions
  • actions/checkout v1 composite
.github/workflows/main-no-deploy.yml actions
  • actions/checkout v2 composite
.github/workflows/main.yaml actions
  • actions/checkout v2 composite
  • peaceiris/actions-gh-pages v3 composite
DESCRIPTION cran
  • bookdown * imports
  • bslib * imports
  • downlit * imports
  • geocompkg * imports
  • magick * imports
  • spData * imports
.github/workflows/qgis-ext.yaml actions
  • actions/checkout v2 composite

Score: 11.922415794328014