---
output: github_document
---

<!-- README.md is generated from README.Rmd. Please edit that file - rmarkdown::render('README.Rmd', output_format = 'github_document', output_file = 'README.md') -->

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

# Geocomputation with R  

[![Build Status](https://travis-ci.org/Robinlovelace/geocompr.svg?branch=master)](https://travis-ci.org/Robinlovelace/geocompr) [![](https://img.shields.io/docker/automated/robinlovelace/geocompr.svg)](https://hub.docker.com/r/robinlovelace/geocompr/builds/)

# Introduction

This repository hosts the code underlying Geocomputation with R, a book by [Robin Lovelace](https://www.robinlovelace.net/), [Jakub Nowosad](https://nowosad.github.io/), and [Jannes Muenchow](http://www.geographie.uni-jena.de/en/Muenchow.html):

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

This book has been published by [CRC Press](https://www.crcpress.com/9781138304512) in the [R Series](https://www.crcpress.com/Chapman--HallCRC-The-R-Series/book-series/CRCTHERSER). 
The online version of this book is free to read at https://geocompr.robinlovelace.net/.

## 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.name/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/Robinlovelace/geocompr/issues)).

Please see [our-style.md](https://github.com/Robinlovelace/geocompr/blob/master/our-style.md) for the book's style.

```{r, 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/Robinlovelace/geocompr/blob/master/our-impact.csv).

## Reproducing the book

To ease reproducibility, this book is also a package. Installing it from GitHub will ensure all dependencies
to build the book are available on your computer (you need [**devtools**](https://github.com/hadley/devtools)):

```{r, eval=FALSE, message=FALSE}
install.packages(devtools)
devtools::install_github("geocompr/geocompkg")
```

You need a recent version of the GDAL, GEOS, Proj.4 and UDUNITS libraries installed for this to work on Mac and Linux. See the **sf** package's [README](https://github.com/edzer/sfr) for information on that.

Once the dependencies have been installed you should be able to build and view a local version the book with:

```{r, eval=FALSE}
bookdown::render_book("index.Rmd") # to build the book
browseURL("_book/index.html") # to view it
```

<!-- The code associated with each chapter is saved in the `code/chapters/` folder. -->
<!-- `source("code/chapters/07-transport.R")` runs run the code chunks in chapter 7, for example. -->
<!-- These R scripts are generated with the follow command which wraps `knitr::purl()`: -->

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

## Running geocompr code in docker

To ease reproducibility we have set-up a docker image ([robinlovelace/geocompr](https://hub.docker.com/r/robinlovelace/geocompr/) on docker hub) containing all the dependencies needed to reproduce the book.
After you have [installed docker](https://www.docker.com/community-edition#/download) and set-it up on [your computer](https://docs.docker.com/install/linux/linux-postinstall/) you should be able to reproduce the entire book with the following steps (resulting in output shown below):

```bash
# download repo with Windows Powershell or a Unix terminal
git clone https://github.com/Robinlovelace/geocompr.git 
# or download manually from here:
# https://github.com/Robinlovelace/geocompr/archive/master.zip
cd geocompr # navigate into the repo
# on linux and mac:
docker run -d -p 8788:8787 -v $(pwd):/home/rstudio/data -e USERID=$UID -e PASSWORD=pickASafePassWord --name rstudio robinlovelace/geocompr

# on windows:
docker run -d -p 8787:8787 -v ${pwd}:/home/rstudio/data -e PASSWORD=safepassword robinlovelace/geocompr
```

If it worked you should be able to open-up RStudio server by opening a browser and navigating to
http://localhost:8787/ resulting in an up-to-date version of R and RStudio running in a container.



![](https://user-images.githubusercontent.com/1825120/39538109-9b50e7ac-4e33-11e8-93b3-e00e95a79294.png)

If you see something like this after following the steps above, congratulations: it worked!
See [github.com/rocker-org](https://github.com/rocker-org/rocker/wiki/Using-the-RStudio-image#running-rstudio-server) for more info.

From this point to *build* the book you can open projects in the `data` directory from the project box in the top-right hand corner, and  knit `index.Rmd` with the little `knit` button above the the RStudio script panel (`Ctl+Shift+B` should do the same job).

## 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}
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, message=FALSE, warning=FALSE, fig.show='hide'}
# source("code/cranlogs.R")
# source("code/sf-revdep.R")
# source("code/08-urban-animation.R")
# source("code/08-map-pkgs.R")
```

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

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


```{r, 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)
}
```


## Book statistics

An indication of the book's progress over time is illustrated below (to be updated roughly every week as the book progresses).

```{r gen-stats, echo=FALSE, message=FALSE, warning=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}
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))
```

Book statistics: estimated number of pages per chapter over time.

## Citations

To cite packages used in this book we use code from [Efficient R Programming](https://csgillespie.github.io/efficientR/):

```{r gen-cite, warning=FALSE}
# geocompkg:::generate_citations()
```

This generates .bib and .csv files containing the packages.
The current of packages used can be read-in as follows:

```{r pkg_df, message=FALSE}
pkg_df = readr::read_csv("extdata/package_list.csv")
```

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
```

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

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

We use Zotero because it is a powerful open source reference manager that integrates well with the **citr** package.
As described in the GitHub repo [Robinlovelace/rmarkdown-citr-demo](https://github.com/Robinlovelace/rmarkdown-citr-demo).

## References

```{r}
knitr::kable(pkg_df)
```

