10.1 Introduction

Chapter 1 established that geocomputation is not only about using existing tools, but developing new ones, “in the form of shareable R scripts and functions”.This chapter teaches these building blocks of reproducible code.It also introduces low-level geometric algorithms, of the type used in Chapter 9.Reading it should help you to understand how such algorithms work and to write code that can be used many times, by many people, on multiple datasets.The chapter cannot, by itself, make you a skilled programmer.Programming is hard and requires plenty of practice (Abelson, Sussman, and Sussman 1996):

To appreciate programming as an intellectual activity in its own right you must turn to computer programming; you must read and write computer programs — many of them.

There are strong reasons for moving in that direction, however.51The advantages of reproducibility go beyond allowing others to replicate your work:reproducible code is often better in every way than code written to be run only once, including in terms of computational efficiency, scalability and ease of adapting and maintaining it.

Scripts are the basis of reproducible R code, a topic covered in Section 10.2.Algorithms are recipes for modifying inputs using a series of steps, resulting in an output, as described in Section 10.3.To ease sharing and reproducibility, algorithms can be placed into functions.That is the topic of Section 10.4.The example of finding the centroid of a polygon will be used to tie these concepts together.Chapter 5 already introduced a centroid function st_centroid(), but this example highlights how seemingly simple operations are the result of comparatively complex code, affirming the following observation (Wise 2001):

One of the most intriguing things about spatial data problems is that things which appear to be trivially easy to a human being can be surprisingly difficult on a computer.

The example also reflects a secondary aim of the chapter which, following Xiao (2016), is “not to duplicate what is available out there, but to show how things out there work”.