20 Writing a Spatial Data Science Project
By the end of this chapter you should be able to:
- Tell data from information, and place both in the DIKW pyramid.
- Describe the data science workflow and where data come from.
- Explain reproducibility, replicability, and open science.
- Explain why spatial data need their own methods, and what to check because of it.
- Write each section of a spatial data science project, from research question to references.
- Explain what makes a project spatial data science, and not just data science with a map.
You have now learned to get data, tidy it, map it, describe it, and test it. This chapter is about putting those pieces together into a project that someone else can read, trust, and rerun. We start with the ideas underneath: what data, information, and knowledge are, where data come from, and what makes an analysis science. Then we walk through a real project, on house values in North Carolina, section by section.
20.1 No information without data
The writer and programmer Daniel Keys Moran put the first idea briefly: you can have data without information, but you can’t have information without data. Raw data become information only after they are processed, organized, and interpreted.
| Data | Information | |
|---|---|---|
| What it is | Raw and unprocessed | Processed, organized data with meaning |
| What it’s for | The basis for analysis | Supporting decisions and giving insight |
| Value | Little on its own | Directly valuable and actionable |
| Examples | Numbers, dates, measurements, text | Reports, summaries, insights, conclusions |
A list of hourly temperatures is data. A forecast that says “bring an umbrella this afternoon” is information.
20.1.1 The DIKW pyramid
The DIKW pyramid takes the idea further, in four levels (Figure 20.1). Each builds on the one below:
- Data: facts and figures.
- Information: data organized to be useful.
- Knowledge: information built up and tested over time and across many situations.
- Wisdom: principles, reasoning, and knowledge applied to judge what is true and right.
Data science is using data to gain information or knowledge about the world. It mostly works on the bottom levels of the pyramid, and helps people climb toward the top.
20.2 The data science process
Chapter 6 introduced the data science workflow from R for Data Science: import the data, tidy it, then cycle through transform, visualize, and model until you understand it, and finally communicate the results. The middle loop repeats, and programming runs through every step. A project write-up is the “communicate” step, but a good one shows all the others too.
20.2.1 Big data
Big data is often described by three Vs:
- Volume: the sheer amount, from terabytes of records, transactions, and files up.
- Velocity: how fast it arrives, from batches to near-real-time feeds and live streams.
- Variety: the mix of structured tables, semi-structured JSON, and unstructured text and images.
Many spatial datasets, such as satellite imagery or the GPS traces from phones, score high on all three.
20.2.2 Where data come from
| Sources | Formats |
|---|---|
| Authoritative: federal, state, county, and local government | Files: GeoJSON, shapefiles, CSV |
| Web scraping: social media, live feeds, news | API calls: data on demand (Chapters 13 and 14) |
| The Internet of Things: sensors streaming readings | Images, text, and 3D formats |
| Real-time analytics feeds |
Government agencies are usually the most authoritative sources. Also note whether a dataset is static, a fixed snapshot, or dynamic, continually updated, because a dynamic source may give different data the next time you run your code.
20.3 Science: reproducibility and replicability
Spatial data science is still science. It builds on a body of knowledge, follows the scientific method, and rests on empirical evidence. Two words describe whether others can trust and build on a result:
- Reproducible: the same data and methods give the same results. Anyone can rerun your analysis and get your numbers.
- Replicable: a new study, with different data, answering the same question, gets consistent results.
Open science makes both possible: open access (papers anyone can read), open data, open methods, open-source software such as R and RStudio, open peer review, and open educational resources (like this book).
R Markdown, from Chapter 2, is a reproducibility tool. It keeps data loading, code, results, and write-up in one document, so anyone with the file and the data can knit it and get the same report.
20.4 Why spatial data are special
Location links observations together, so spatial data need their own methods.
What makes them special:
- The first law of geography: near things are more related than distant things.
- Spatial autocorrelation: values cluster, so observations are not independent. Neighboring counties tend to have similar house values.
- Spatial heterogeneity: relationships change from place to place. Remote work may matter more for house values near cities than in rural counties.
What it means for your analysis:
- Clustered residuals make standard tests overconfident. Map your model’s residuals and test them with Moran’s I (Chapter 22).
- Scale and zoning matter. County and tract results can differ: the modifiable areal unit problem.
- Projection matters. Distances and areas depend on the coordinate system (Chapter 12).
20.5 Building blocks of a project
Every project has the same building blocks:
| Section | What goes in it |
|---|---|
| Introduction | Your research question and why it matters |
| Background | What earlier work found, and how it relates to your question |
| Data and methods | Your data, cited and described; the code that tidies them; maps and descriptive statistics |
| Results | Maps, graphs, and statistics that help answer the question |
| Conclusion | Your answer, as well as you can give it; limitations; what you’d do differently |
| References | Every source you used |
We’ll go through each one using an example project, written in R Markdown, titled What Demographic Variables May Influence Median House Value for North Carolina in 2020? You met its models in Chapter 19.
20.5.1 Introduction: the research question
The research question drives everything else. A good one is:
- Specific and focused. Include the place and time where they matter.
- Answerable, even if you end up not able to answer it fully.
- Worth asking. Explain why it matters.
It doesn’t have to be phrased as a question, but that often helps.
The example’s introduction says that the project examines which demographic factors might relate to median home value in North Carolina’s counties in 2020: in particular, whether the percentage of people working from home is related to home value, and by how much it raises or lowers it. It names the other variables it will bring in (percent white alone, median age, and median income) and says the project will explore the data, build a model, and discuss how well the model fits, statistically and spatially, using residuals. A reader knows the place, the time, the variables, and the plan by the end of the second paragraph.
Which is the better research question, and why? (a) “What affects house prices?” (b) “Is the share of residents who work from home related to median house value in North Carolina’s counties in 2020?” How would you make (b) more spatial?
20.5.2 Background: build on earlier research
The background shows you’ve read what came before. What have others found? How does it shape your question, your data, or your methods?
The example’s background notes that house prices and cost of living have clear geographic patterns, but are not a common topic for geographers. It summarizes a study by Campbell and James that built a housing cost index for North Carolina’s counties, the ratio of median home value to median household income, and tested whether second homes in the mountains and at the beach push costs up. That earlier work suggests variables to include and a spatial pattern to look for.
20.5.3 Data and methods: show your work
In data and methods, you show your work:
- Cite the source of your data: which agency, which survey, which year, and how you got it.
- Include the code that loads and tidies the data.
- Describe the data with summary statistics and maps.
# Load the libraries used in this research
library(tidyverse)
library(sf)
library(tmap)
# Load the 2020 NC counties data
ncCounties <- read_sf("...")
glimpse(ncCounties)glimpse() shows 100 rows, one per county, and the columns. Then a summary and a map of the dependent variable, median home value, and a map of each independent variable (Figure 19.3). Mapping each variable before modeling it is how you notice patterns, such as higher incomes and more remote work around the Triangle and Charlotte, and problems, such as a county with a missing value.
20.5.4 Results: model your question
A model is a simplified representation of a real-world process. The results section fits models that test your question, and reports them with maps, graphs, and statistics.
The example’s first model tests whether the share of people working from home is related to median house value. Each additional percentage point working from home goes with about $36,564 higher median house value, with an adjusted R² of 0.74. A second model adds median income, median age, and percent white, and raises the adjusted R² to 0.86 (Chapter 19).
20.5.5 Check the model: map the residuals
A spatial results section doesn’t end with the model summary. Check the model by mapping its residuals, each county’s observed value minus the model’s prediction:
- Fit the model.
- Map the residuals. Where does the model over- or under-predict?
- Test them with Moran’s I (Chapter 22). Do the residuals cluster more than chance would produce?
- Revise the model. If they cluster, add explanatory variables or fit a spatial lag or spatial error model.
Repeat steps 2 to 4 until the residuals no longer cluster.
20.5.6 A second method: comparing regions with ANOVA
Regression asks how one variable changes with another. ANOVA (Chapter 18) asks whether a variable’s mean differs across three or more groups. In a project on North Carolina, the groups can be regions, such as the mountains, the Piedmont, and the coastal plain, and the variable median male age by county. aov(age ~ region) tests whether the regions differ, and TukeyHSD() shows which ones. Because the groups are places, map them, so the reader can see the regional pattern.
20.5.7 Conclusion: answer the question
The conclusion should:
- Answer your question, or explain honestly why you couldn’t.
- Discuss limitations. What could make the results misleading?
- Say what you’d do differently next time, and what future work should try.
The example’s conclusion does all three. It answers the question: three variables (percent working from home, percent white, and median income) are related to median house value, and each extra percentage point working from home adds potentially over $20,000. It is honest about the spatial fit: the residuals vary a lot across the state, with some mountain, coastal, and rural counties not following the model, which suggests missing variables. It names limitations: medians hide the range within each county, and the direction of the relationship is unclear (does remote work raise prices, or do people who can work from home simply earn more?). And it proposes future work: smaller units such as census tracts, more variables such as job type and education, and comparisons over time or with similar states.
20.5.8 References
List every source you used, in a consistent style, and cite them in the text. That includes data sources, such as “U.S. Census Bureau, American Community Survey 5-year estimates”, and R packages, which you can cite with citation("tidycensus").
20.6 So, what is spatial data science?
Spatial data science combines three things:
- spatial data,
- maps and visualizations, and
- spatial analysis.
Done well, it is also open, reproducible, and replicable, and it is often built on big data.
One caution. Using spatial data doesn’t by itself make a project spatial data science. A regression on county data that never maps or tests its residuals is ordinary statistics that happens to use places. You also need spatial analysis: a question with spatial aspects, such as the regional ANOVA, the residual map, or a test for spatial autocorrelation.
20.7 Check your understanding
A list of every county’s median house value, with no summary or map, is:
Which level sits at the top of the DIKW pyramid?
Running the same code on the same data and getting the same results is called:
The three Vs of big data are volume, velocity, and:
Which section of a project states the research question?
A research question should always be phrased as a question.
In which section do you discuss what you would do differently next time?
Any project that uses spatial data is spatial data science.
20.8 Summary
- Data are raw values; information is data organized and interpreted. The DIKW pyramid adds knowledge and wisdom on top.
- The data science workflow is import, tidy, a loop of transform, visualize, and model, then communicate. Big data is described by volume, velocity, and variety.
- Data come from authoritative agencies, web scraping, sensors, and feeds, as files or through APIs, and can be static or dynamic.
- Science should be reproducible (same data and methods, same results) and replicable (new data, consistent results). Open science and R Markdown make that easier.
- Spatial data are special because of the first law of geography, spatial autocorrelation, and spatial heterogeneity. Map and test residuals, and watch scale, zoning, and projection.
- A project has an introduction (the research question), background, data and methods, results, a conclusion, and references.
- Spatial data science combines spatial data, maps, and spatial analysis. Spatial data alone aren’t enough.
20.9 Exercises
- Climb the pyramid. Pick a dataset you’ve used this semester. Give one example of it at each level of the DIKW pyramid.
- Sharpen a question. Rewrite “Is pollution bad for health?” as a specific, answerable, spatial research question about North Carolina. Name the place, time, units of analysis, and variables.
- Find the background. Search Google Scholar for one published study related to your question from Exercise 2. Write two sentences on what it found and how it shapes your own question or methods.
- Data and methods. For your question, list each dataset you’d need, who publishes it, whether it’s static or dynamic, and how you’d get it into R.
- Peer review. Swap project drafts with a classmate. For each building block in Table 20.3, write one thing that works and one thing to improve. Is their project spatial data science, by the definition in this chapter?
20.10 Further reading
- R for Data Science (2nd ed.), by Hadley Wickham, Mine Çetinkaya-Rundel, and Garrett Grolemund, free at https://r4ds.hadley.nz. The introduction describes the data science workflow, and the “Quarto” chapters cover writing reproducible reports.
- National Academies of Sciences, Engineering, and Medicine (2019). Reproducibility and Replicability in Science. National Academies Press. Free at https://doi.org/10.17226/25303. The source of the definitions used in this chapter.
- Campbell, H. S., Jr., and James, R. D. (2021). “Place, Space, and Cost of Living in North Carolina: A Research Note.” Southeastern Geographer 61(1): 81–104. The study the example project builds on.
read.csv() or
read_csv().
Application Programming Interface: a set of rules for how one program
asks another for data or services, such as your R script asking the
Census Bureau’s server for a table.
Data that are continually updated, so the same request may return
different data later. Static data are a fixed snapshot.
The integrated development environment (IDE) where you write and run R.
R does the computing; RStudio is the workspace around it.
A document format (.Rmd) that mixes formatted text with
chunks of R code. Knitting it runs the code and builds a finished
report.
To build an R Markdown file into a finished document (HTML, PDF, or
Word). Knitting reruns every code chunk from the top in a fresh R
session.
One thing that was measured or recorded, such as a student, a county, or
a flight. In a data frame, each row is an observation.
Waldo Tobler’s statement that “everything is related to everything else,
but near things are more related than distant things.” It is the idea
behind spatial autocorrelation.
The tendency for things that are close together to be more alike than
things that are far apart, such as neighboring counties having similar
incomes.
The assumption, built into most standard statistics, that knowing one
observation tells you nothing about another. Data about places usually
break it, because nearby places tend to be alike.
The idea that relationships between variables change from place to
place. A link that is strong in one city may be weak, or reversed, in
another.
An observation’s actual value minus the value a model predicts for it.
Map them to see where a model fits poorly.
A global measure of spatial autocorrelation, from −1 (dispersed) through
0 (random) to +1 (clustered), with a p-value.
The level of detail at which you study something: addresses,
neighborhoods, counties, or states. A pattern that is clear at one scale
can vanish or reverse at another.
A small area of about 1,200 to 8,000 people (4,000 on average), drawn to
be fairly stable over time. The workhorse unit for neighborhood
analysis.
The way results can change when the same individual data are grouped
into different areas, either larger or smaller ones or the same size
with different boundaries.
A method for flattening the curved graticule onto a flat map. Every
projection distorts shape, area, distance, or direction.
The rules that tie coordinates to places on the Earth, including how the
round Earth is flattened onto a map (the projection). Layers must share
a coordinate system before you can combine them.
In R, a named piece of memory that holds data, such as
months <- 12. In a dataset, a measured characteristic,
such as median income; each Census variable has a code.
The middle value when values are sorted, so half are above and half
below. Unlike counts, medians can’t be added across areas.
The arrangement of objects in space: clustered, random, or dispersed.
One number that describes many values, such as their mean, median,
maximum, or count. summarize() calculates them.
The outcome a model explains, y. It goes on the left of the
~ in an R formula.
A variable used to explain the dependent variable, x. It goes
on the right of the ~.
A value that is unknown, written NA (“not available”) in R.
Most calculations with NA give NA; test for it
with is.na().
R-squared lowered a little for each independent variable, so adding
useless variables can’t make a model look better. Use it to compare
models.
The weighted average of an observation’s neighbors’ values, calculated
with row-standardized weights. lag.listw() in spdep.
A spatial regression model that allows the errors of neighboring
observations to be correlated.
A statistical model of how one variable (such as home price) changes
with one or more others (such as distance to downtown).
Analysis of variance: a statistical test of whether the averages of
three or more groups differ, such as median age in three regions. It
compares variation between groups with variation within them.
The Census Bureau’s continuous survey of a sample of households every
year. It asks many more questions than the decennial census, but every
value is an estimate with a margin of error.
ACS estimates that pool 60 months of responses. They are the most
reliable ACS product and the only one for tracts and block groups. An
estimate labeled 2022 describes 2018 to 2022.
A bundle of code, written by other users, that adds new functions to R.
Install it once with install.packages(), then load it in
each session with library().
The newer successor to R Markdown, from the same developers. Quarto
files end in .qmd. This book is written in Quarto.