A Criminologist's Guide to R cover

432 pages · 2022

Catalog title1st Edition

A Criminologist's Guide to R

Crime by the Numbers

By Jacob Kaplan

Published
December 15, 2022
Imprint
Chapman and Hall/CRC
Edition
1st Edition
ISBN
9781003279211

Overview

About this book

A Criminologist's Guide to R: Crime by the Numbers introduces the programming language R and covers the necessary skills to conduct quantitative research in criminology. By the end of this book, a person without any prior programming experience can take raw crime data, be able to clean it, visualize the data, present it using R Markdown, and change it to a format ready for analysis. A Criminologist's Guide to R focuses on skills specifically for criminology such as spatial joins, mapping, and scraping data from PDFs, however any social scientist looking for an introduction to R for data analysis will find this useful.

Key Features:

Introduction to RStudio including how to change user preference settings. Basic data exploration and cleaning – subsetting, loading data, regular expressions, aggregating data. Graphing with ggplot2. How to make maps (hotspot maps, choropleth maps, interactive maps). Webscraping and PDF scraping. Project management – how to prepare for a project, how to decide which projects to do, best ways to collaborate with people, how to store your code (using git), and how to test your code.

Subjects

Law, Mathematics & Statistics

Inside the book

Table of contents

Select a chapter to read its abstract.

Part IIntroduction

Pages: 54

No chapter abstract available.

Chapter 1A soup to nuts project example

Pages: 10

Before we get into exactly how to use R, we'll go over a brief example of a kind of data project that you'd do in the real world. For this chapter we'll look at FBI homicide data that you can download here. 1 The file is called “shr_1976_2020.rds”.

Chapter 2Introduction to R and RStudio

Pages: 22

This chapter helps the readers to learn to open a data file in R. RStudio is the interface we use to work with R. The chapter looks at RStudio and provides some brief code to load in some crime data and start exploring it. A function is a bunch of code that has been assigned to an object. Downloading a package through R code uses - like pretty much everything else in R - a function. The summary() function gives a six-number summary of each numeric or Date column in the data. The six values it returns for numeric and Date columns are: the minimum value, the value at the 1st quartile, the median value, the mean value, the value at the 3rd quartile, and the max value.

Chapter 3Data types and structures

Pages: 12

This chapter presents three main data types that are important to know for using R to do research: numeric, character, and logical. A numeric type is a number, and this includes both integers like 2 and decimals like 2.5. A character is just a word or a set of words. Finally, a logical data type is just a true or false value, though in R it must be written all in capital letters: TRUE or FALSE. This is also referred to as a Boolean value. The chapter looks in detail about two important data structures - vectors and data.frames. Data structures each operate a little differently from each other so it's good to understand what they are and how they work. The chapter also presents two other data structures. The first data structure is a list. The other type of data structure is a matrix.

Chapter 4Reading and writing data

Pages: 8

An ASCII file is just a text file and the fixed-width part means that each row has the exact same number of characters. Each fixed-width ASCII file comes with what is called a “setup” file, which is some code that tells the program criminologists are reading the data into how to separate columns and when to replace the numbers that indicate the state with the actual state name. This chapter presents some files, which are available for download: fatal-police-shootings-data.csv, fatal-police-shootings-data.dta, fatal-police-shootings-data.sas, fatal-police-shootings-data.sav, sqf-2019.xlsx, sf_neighborhoods_suicide.rda, and shr_1976_2020.rds. Many data sets, particularly older government data, will not come as. rda or. rds files but rather as Excel, Stata, SAS, SPSS, or fixed-width ASCII files. The chapter covers how to read these formats into R as well as how to save data into these formats.

Part IIProject Management

Pages: 72

No chapter abstract available.

Chapter 5Mise en place

Pages: 14

If you're familiar with cooking you might have heard the phrase mise en place, 1 which is French for “everything in its place.” In cooking this concept means that you get everything - ingredients, pots, pans, bowls, utensils, etc. - needed to cook that item ready before you begin cooking. This saves time as you have everything you need in front of you and can just cook from start to finish without stopping to find something. This is also a useful idea in programming, especially when you're programming to conduct research.

Chapter 6Collaboration

Pages: 6

Code review is a useful technique for reducing the number of mistakes as it is a check on the work before using the code for real. Code review generally involves having one person who writes the code send it to another person who checks the code for any potential mistakes or issues. For the person having their code reviewed, having comments explaining the what and why of the code will help the reviewer quickly go through the code. For code review to be most efficient, authors recommend developing some rules with your collaborators to specify how and when code review is done. They will talk about documentation in two ways, through comments, which focus on specific parts of code, and vignettes, which document the project more broadly. Stopping to write a comment on something that seems obvious at the time interrupts the flow of writing code and slows down your work.

Chapter 7R Markdown

Pages: 16

When conducting research your end product is usually a Word Document or a PDF which reports on the research you've done, often including several graphs or tables. In many cases people do the data work in R, producing the graphs or numbers for the table, and then write up the results in Word or LaTeX. When you're making a report for a general audience you generally only want to show the output (e.g. a graph or table), not the code that you used. At early stages in writing the report or when you're collaborating with someone who wants to see your code, it is useful to include the code in the R Markdown output. You can also include R code directly in the text of your document and it will return the output of that code.

Chapter 8Testing your code

Pages: 14

This chapter covers how to write code that tests other code. Readers can also take this kind of approach when testing functions which ideally are the way they write code. As with their normal R script, they can have separate testing scripts (a testing script is a normal R script which people use specifically for testing code but doesn't actually function any different) for each major part of the code that they are testing. As with the R scripts for their code, this is simply a way to organize their work, and doesn't affect the testing. At the start authors have some code that loads the data that they will test this isn't in the setup file since the code is for this specific test script (though it could be in the setup.R file and the results would be the same). In these cases there are relatively few opportunities to use unit tests to check the readers code.

Chapter 9Git

Pages: 20

This chapter covers Git, which is a way to have version control for the code, like a programming version of Dropbox, but with a few added features. There are four main processes one need to know for a basic understanding of Git: checkout, add and commit, push, and pull. The chapter explains how to use Git through buttons on RStudio so one don't necessarily need to know these commands in Git, but it's useful to know enough to talk about them and ask questions if needed. A public repository is one that anyone can look at on GitHub, download the code/files, and make any changes they want. Everything is largely automated so accepting changes is a breeze. There is no hard rule that it must be short, but the general convention is that each commit is relatively small and thus the description of the message can be short.

Part IIIClean

Pages: 92

No chapter abstract available.

Chapter 10Subsetting: Making big things small

Pages: 32

For this chapter you'll need the following file, which is available for download here 1 : offenses_known_yearly_1960_2020.rds.

Chapter 11Exploratory data analysis

Pages: 22

For this chapter you'll need the following files, which are available for download here 1 : ucr2017.rda and offenses_known_yearly_1960_2020.rds.

Chapter 12Regular Expressions

Pages: 24

Many word processing programs like Microsoft Word or Google Docs let you search for a pattern - usually a word or phrase - and it will show you where on the page that pattern appears. It also lets you replace that word or phrase with something new. R does the same using the function grep() to search for a pattern and tell you where in the data it appears, and gsub(), which lets you search for a pattern and then replace it with a new pattern.

Chapter 13Reshaping data

Pages: 12

For this chapter you'll need the following file, which is available for download here 1 : sqf-2019.xlsx. This file was initially downloaded from the New York City Police Department's page here 2 .

Part IVVisualize

Pages: 114

No chapter abstract available.

Chapter 14Graphing with ggplot2

Pages: 20

The “gg” part of ggplot2 stands for “grammar of graphics”, which is the idea that most graphs can be made using the same few “pieces.” The data we will work on is data about alcohol consumption in US states from 1977-2017 from the National Institutes of Health. It contains the per capita alcohol consumption for each state for every year. Their method to determine per capita consumption is amount of alcohol sold / number of people aged 14+ living in the state. Some useful types of graphs are: geom_point();geom_line();geom_bar(); and geom_smooth(). The chapter presents a time-series of beer consumption in Pennsylvania. Many time-series plots show multiple variables over the same time period.

Chapter 15More graphing with ggplot2

Pages: 36

For this chapter you'll need the following file, which is available for download here 1 : fatal-police-shootings-data.csv.

Chapter 16Hotspot maps

Pages: 16

Hotspot maps are used to find where events or places e.g. These maps are frequently used by police departments, particularly in determining where to do hotspot policing (which focuses patrols on high-crime areas). Hotspot maps also often turn into population maps, where the dots indicate where people live rather than where the risk of something is. For example, a street with several apartment buildings will likely have more crimes (and thus have more dots on a hotspot map) than a street with only single-family homes. So not knowing the context of an area can make hotspot maps very misleading. Authors explore these issues in more detail throughout the lesson but keep in mind these risks as readers make their own hotspot maps. The authors will make hotspot maps using data on suicides in San Francisco between 2003 and 2017.

Chapter 17Choropleth maps

Pages: 18

For this chapter you'll need the following files, which are available for download here 1 : san_francisco_suicide_2003_2017.csv, san_francisco_neighborhoods.dbf, san_francisco_neighborhoods.prj, san_francisco_neighborhoods.shp, san_francisco_neighborhoods.shx.

Chapter 18Interactive maps

Pages: 22

While maps of data are useful, their ability to show incident-level information is quite limited. They tend to show broad trends, where crime happened in a city, rather than provide information about specific crime incidents. While broad trends are important, there are significant drawbacks about being unable to get important information about an incident without having to check the data. An interactive map bridges this gap by showing trends while allowing one to zoom into individual incidents and see information about each incident. Interactive maps are popular in large police departments, such as Philadelphia and New York City. They allow easy understanding of geographic patterns in the data and, importantly, allow such access to people who do not have the technical skills necessary to interact with the data itself. If nothing else, learning interactive maps may help one with a future job.

Part VCollect

Pages: 76

No chapter abstract available.

Chapter 19Webscraping with rvest

Pages: 8

If I ever stop working in the field of criminology, I would certainly be a baker. So for the next few chapters we are going to work with “data” on baking. What we'll learn to do is find a recipe from the website All Recipes 1 and webscrape the ingredients and directions of that recipe. 2

Chapter 20Functions

Pages: 6

So far, we have been writing code to handle specific situations, such as subsetting a single data set, often using other people's functions. In cases where you want to reuse the code, it is unwise to simply copy and paste the code and make minor changes to handle the new data. Instead we want something that is able to take multiple values and perform the same action (subset, aggregate, make a plot, webscrape, etc.) on those values. We've used lots of other people's function throughout this book, and in this chapter we'll learn how to create our own.

Chapter 21For loops

Pages: 6

We will often want to perform the same task on a number of different items, such as cleaning every column in a data set. One effective way to do this is through “for loops”. Earlier in this book we learned how to scrape the recipe website All Recipes. 1 We did so for a single recipe. If we wanted to get a feast's worth of recipes, typing out each recipe would be slow, even with the function we made in Section 20.3. In this chapter we will use a for loop to scrape multiple recipes very quickly.

Chapter 22Scraping tables from PDFs

Pages: 18

For this chapter you'll need the following file, which is available for download here 1 : usbp_stats_fy2017_sector_profile.pdf.

Chapter 23More scraping tables from PDFs

Pages: 24

For this chapter you'll need the following files, which are available for download here 1 : AbbreRptCurrent.pdf and PregnantFemaleReportingCurrent.pdf.

Chapter 24Geocoding

Pages: 12

Several recent studies have looked at the effect of marijuana dispensaries on crime around the dispensary. For these analyses they find the coordinates of each crime in the city and see if it occurred in a certain distance from the dispensary. This chapter covers how to geocode addresses. Geocoding is the process of taking an address and getting the longitude and latitude coordinates of that address. Most of the columns are just the address broken into different pieces so are mostly repeating the address again in multiple columns. The minimum and maximum are very similar to each other for both longitude and latitude so that's a sign that it geocoded correctly.