Project 2

Project 2

Image cite: https://www.pngitem.com/middle/wbxhT_handcuffs-criminal-defense-lawyer-arrest-clip-art-arrest/

The topic for this project I chose today was about the NYPD Police arrest in 2013. I chose it because I wanted to use the data to explore or determine the usual suspects that are likely to get arrested. This dataset came from The NYPD website. The following variables that are used are Age, City, Weight, Timestop and Race. 

Dataset: https://www.nyc.gov/site/nypd/stats/reports-analysis/stopfrisk.page

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(dplyr)
library(ggplot2)
library(treemapify)
library(scales)

Attaching package: 'scales'

The following object is masked from 'package:purrr':

    discard

The following object is masked from 'package:readr':

    col_factor
library(plotly)

Attaching package: 'plotly'

The following object is masked from 'package:ggplot2':

    last_plot

The following object is masked from 'package:stats':

    filter

The following object is masked from 'package:graphics':

    layout
setwd("~/Documents/Data 101/:Users:terrymensah:Documents:Data 101")

Police_Arrests_2013 <- read_csv(
  "Police_Arrests_2013.csv",
  skip = 1,
  locale = locale(encoding = "Windows-1252")
)
Rows: 191851 Columns: 112
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (85): recstat, inout, trhsloc, crimsusp, perstop, typeofid, explnstp, ot...
dbl (21): year, pct, ser_num, datestop, timestop, perobs, compyear, comppct,...
lgl  (6): dob, rescode, premtype, aptnum, state, zip

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
clean_arrests <- Police_Arrests_2013 %>%
  mutate(
    across(where(is.character), ~ na_if(str_trim(.x), "")),
    age = as.numeric(age),
    age = if_else(between(age, 1, 100), age, NA_real_),
    city = recode(city, "STATEN IS" = "STATEN ISLAND")
  ) %>%
  filter(arstmade %in% c("Y", "N")) %>%
  select(where(~ !all(is.na(.x))))

head(clean_arrests) 
# A tibble: 6 × 106
   year   pct ser_num datestop timestop recstat inout trhsloc perobs crimsusp   
  <dbl> <dbl>   <dbl>    <dbl>    <dbl> <chr>   <chr> <chr>    <dbl> <chr>      
1  2013     1       2  1012013      452 1       I     T            6 GRAND LARC…
2  2013     1       3  1012013      315 1       I     T           15 GRAND LARC…
3  2013     1       7  1012013      300 1       I     T           10 ROBBERY    
4  2013     1      11  1012013     1212 A       O     P            1 ROBBERY    
5  2013     1      12  1012013     2300 A       O     P            5 BURGLARY   
6  2013     5       1  1012013      115 1       O     P            1 ROBBERY    
# ℹ 96 more variables: perstop <chr>, typeofid <chr>, explnstp <chr>,
#   othpers <chr>, arstmade <chr>, arstoffn <chr>, sumissue <chr>,
#   sumoffen <chr>, compyear <dbl>, comppct <dbl>, offunif <chr>,
#   officrid <chr>, frisked <chr>, searched <chr>, contrabn <chr>,
#   adtlrept <chr>, pistol <chr>, riflshot <chr>, asltweap <chr>,
#   knifcuti <chr>, machgun <chr>, othrweap <chr>, pf_hands <chr>,
#   pf_wall <chr>, pf_grnd <chr>, pf_drwep <chr>, pf_ptwep <chr>, …

Importing and Cleaning the Dataset. This chunk loads the required R packages, imports the 2013 police stop dataset and cleans the missing values and corrects city names. 


clean_arrests <- clean_arrests %>%
  mutate(race_full = recode(race,
                            "B" = "Black",
                            "W" = "White",
                            "A" = "Asian/Pacific Islander",
                            "P" = "Black Hispanic",
                            "Q" = "White Hispanic",
                            "I" = "American Indian/Alaska Native",
                            "Z" = "Other",
                            "U" = "Unknown",
                            .default = "Unknown"
  ))

This chunk converts abbreviated race codes into full names and creates a new variable called race_full.

library(ggplot2)
library(dplyr)

clean_arrests %>%
  filter(between(weight, 1, 500)) %>%
  mutate(weight_group = cut(
    weight,
    breaks = c(0, 100, 150, 200, 250, 501),
    labels = c("Under 100", "100-149", "150-199",
               "200-249", "250-500"),
    right = FALSE
  )) %>%
  ggplot(aes(x = weight_group)) +
  geom_bar(fill = "steelblue") +
  labs(
    title = "Weight Distribution in Police Stops (2013)",
    x = "Weight (lbs)",
    y = "Number of People"
  ) +
  theme_minimal() 

This groups individuals into weight categories. I created a bar chart showing the number of people in each category. 

clean_arrests %>%
  filter(!is.na(city)) %>%
  ggplot(aes(x = reorder(city, city,
                         function(x) -length(x)))) +
  geom_bar(fill = "steelblue") +
  coord_flip() +
  labs(
    title = "Distribution of Police Stops by City (2013)",
    x = "City",
    y = "Number of Police Stops"
  ) +
  theme_minimal()

This removes the records with missing city information. I created a bar chart comparing police stops and access cities. 

Chunk #4: Police Stops by City

# Create regression dataset
regression_data <- clean_arrests |>
  mutate(
    age = as.numeric(age),
    weight = as.numeric(weight),
    timestop = as.numeric(timestop),
    stop_hour = floor(timestop / 100) +
      (timestop %% 100) / 60
  ) |>
  filter(
    !is.na(age),
    !is.na(weight),
    !is.na(timestop),
    between(age, 1, 100),
    between(weight, 1, 500),
    between(floor(timestop / 100), 0, 23),
    timestop %% 100 < 60
  ) 

library(tidyverse)


model <- lm(weight ~ age + stop_hour,
            data = regression_data)


ggplot(regression_data,
       aes(x = age, y = weight,
           color = stop_hour)) +
  
  geom_point(alpha = 0.4) +
  
  geom_smooth(
    method = "lm",
    formula = y ~ x,
    se = FALSE,
    color = "blue"
  ) +
  
  scale_color_gradient(
    low = "lightblue",
    high = "darkblue",
    name = "Time of Stop"
  ) +
  
  labs(
    title = "Linear Regression of Age and Weight",
    subtitle = "Police Arrests 2013",
    x = "Age (Years)",
    y = "Weight (Pounds)"
  ) +
  
  theme_minimal()

summary(model)

Call:
lm(formula = weight ~ age + stop_hour, data = regression_data)

Residuals:
    Min      1Q  Median      3Q     Max 
-187.67  -17.17   -2.35   14.53  334.49 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept) 152.113205   0.218190 697.160  < 2e-16 ***
age           0.628120   0.005692 110.353  < 2e-16 ***
stop_hour    -0.036216   0.008802  -4.115 3.88e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 29.18 on 191224 degrees of freedom
Multiple R-squared:  0.06025,   Adjusted R-squared:  0.06024 
F-statistic:  6130 on 2 and 191224 DF,  p-value: < 2.2e-16

I prepared age, weight, and time-of-stop variables. I created a regression model predicting weight using age and stop time. This Displays a scatterplot and summarizes the regression results.

library(tidyverse)
library(knitr)
library(treemapify)
library(plotly)



setwd("~/Documents/Data 101/:Users:terrymensah:Documents:Data 101")

police_arrests <- read_csv(
  "Police_Arrests_2013.csv",
  skip = 1,
  locale = locale(encoding = "Windows-1252"),
  show_col_types = FALSE
)


race_data <- police_arrests |>
  mutate(
    race = recode(
      race,
      "B" = "Black",
      "W" = "White",
      "Q" = "Hispanic (White)",
      "P" = "Hispanic (Black)",
      "A" = "Asian/Pacific Islander",
      "I" = "American Indian/Alaska Native",
      "Z" = "Other",
      "U" = "Unknown"
    )
  ) |>
  count(race, name = "total") |>
  mutate(
    percent = round(total / sum(total) * 100, 1),
    hover_text = paste0(
      "Race: ", race,
      "<br>Records: ", scales::comma(total),
      "<br>Percentage: ", percent, "%"
    )
  ) 


p <- ggplot(
  race_data,
  aes(
    area = total,
    fill = race,
    label = race,
    text = hover_text
  )
) +
  geom_treemap(color = "white", linewidth = 1) +
  geom_treemap_text(
    color = "white",
    place = "centre",
    grow = TRUE,
    reflow = TRUE
  ) +
  scale_fill_brewer(
    palette = "Dark2",
    name = "Race"
  ) +
  labs(
    title = "Distribution of Police Stop Records by Race in 2013",
    subtitle = "Larger rectangles represent more recorded stops",
    caption = "Source: Police_Arrests_2013.csv"
  ) +
  theme_minimal()
Warning in geom_treemap(color = "white", linewidth = 1): Ignoring unknown
parameters: `linewidth`
p

ggplotly(p, tooltip = "text")
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemap() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemap() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemap() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemap() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemap() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemap() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemap() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemap() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemapText() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemapText() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemapText() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemapText() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemapText() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemapText() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemapText() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues
Warning in geom2trace.default(dots[[1L]][[8L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomTreemapText() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues

This counts police stop records for each race category. I created a colored treemap showing the distribution by race. I added interactive information using Plotly.


library(tidyverse)
library(plotly)
library(scales)


time_data <- police_arrests |>
  mutate(
    timestop = as.numeric(timestop),
    hour = floor(timestop / 100),
    time_period = case_when(
      hour >= 5 & hour < 12 ~ "Morning",
      hour >= 12 & hour < 17 ~ "Afternoon",
      TRUE ~ "Evening/Night"
    )
  ) |>
  filter(
    !is.na(timestop),
    between(hour, 0, 23),
    timestop %% 100 < 60
  ) |>
  count(hour, time_period, name = "total") |>
  mutate(
    hover_text = paste0(
      "Hour: ", sprintf("%02d:00", hour),
      "<br>Period: ", time_period,
      "<br>Police Stops: ", comma(total)
    )
  )


p2 <- ggplot(
  time_data,
  aes(
    x = hour,
    y = total,
    color = time_period,
    group = 1,
    text = hover_text
  )
) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 2.5) +
  
  scale_color_manual(
    values = c(
      "Morning" = "orange",
      "Afternoon" = "blue",
      "Evening/Night" = "purple"
    ),
    name = "Time of Day"
  ) +
  
  scale_x_continuous(
    breaks = seq(0, 23, 2)
  ) +
  
  labs(
    title = "Police Stops by Hour of Day in 2013",
    subtitle = "Number of recorded police stops across 24 hours",
    x = "Hour of Day (24-Hour Clock)",
    y = "Number of Police Stops",
    caption = "Source: Police_Arrests_2013.csv"
  ) +
  
  theme_minimal()


p2

ggplotly(p2, tooltip = "text")

I converted police stop times into hourly categories. I grouped stops into morning, afternoon, and evening/night. I created an interactive line graph showing stops throughout the day.