Loading libraries

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.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

Reading in the data sets

closureData <- read_csv("ClosureCases_clean.csv")
## Rows: 34 Columns: 25
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (20): caseNbr, lastName, firstName, Cty, DOB, Gender, Race, Program, dat...
## dbl  (3): Age, lengthRefClsd, Payment
## lgl  (2): restitutionPaid, Notes
## 
## ℹ 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.
intakeData <- read_csv("IntakeCases_clean.csv")
## Rows: 44 Columns: 25
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (23): caseNbr, lastName, firstName, Program, DOB, Gender, dateIncident, ...
## dbl  (2): Age, lengthRef_Intake
## 
## ℹ 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.
refData <- read_csv("ReferralsCases_clean.csv")
## Rows: 58 Columns: 18
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (17): caseNbr, lastName, firstName, Cty, Program, DOB, Gender, dateIncid...
## dbl  (1): lengthIncidentRef
## 
## ℹ 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.
ACRJ <- read_csv("ACRJ_clean.csv")
## Rows: 68 Columns: 15
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (15): caseNbr, Location, caseCategory, caseType, Style, lastName, caseSt...
## 
## ℹ 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.

Renaming variables for the merge

ACRJ <- ACRJ |>
  rename(Status = 7, offenseType = 9, docketNbr = 1, dateIncident = 10) 
#where dateIncident = date of first offense (if multiple)

Removing the case type variable as it is essentially a duplicate of the program variable

closureData <- closureData |>
  subset(select = -caseType)

Changing the class of certain variables to match other data sets needed for the merge

Referral data set

refData <- refData |>
  mutate(Age = as.numeric(Age)) |>
  mutate(lengthIncidentRef = as.numeric(Age))
## Warning: There was 1 warning in `mutate()`.
## ℹ In argument: `Age = as.numeric(Age)`.
## Caused by warning:
## ! NAs introduced by coercion

Intake data set

intakeData <- intakeData |>
  mutate(lengthIncidentRef = as.numeric(lengthIncidentRef))
## Warning: There was 1 warning in `mutate()`.
## ℹ In argument: `lengthIncidentRef = as.numeric(lengthIncidentRef)`.
## Caused by warning:
## ! NAs introduced by coercion

Animation Data

combined_data <- ACRJ |>
  full_join(refData) |>
  full_join(intakeData) |>
  full_join(closureData) |>
  rename(dateClsd = 38)
## Joining with `by = join_by(docketNbr, lastName, Status, Program, dateIncident)`
## Joining with `by = join_by(docketNbr, lastName, Status, Program, dateIncident,
## caseNbr, firstName, DOB, Gender, dateCharged, Age, dateRef, dateReRef,
## lengthIncidentRef, Race, Court, Notes)`
## Joining with `by = join_by(docketNbr, lastName, Program, dateIncident, Outcome,
## caseNbr, firstName, Cty, DOB, Gender, Age, dateRef, dateReRef, Race, Court,
## Notes)`
# Removing observations for which all 3 dates have NA values
# Fixing date format
combined_data <- combined_data |>
  select(-dateCharged, -dateFiled, -dateDivClsd, -dateReRef)|>
  filter(!(is.na(dateIncident) & is.na(dateRef) & is.na(dateClsd) & is.na(dateIntake)))|>
    mutate(dateIncident = as.Date(dateIncident, format = "%m/%d/%y")) |>
    mutate(dateRef = as.Date(dateRef, format = "%m/%d/%y")) |>
    mutate(dateIntake = as.Date(dateIntake, format = "%m/%d/%y")) |>
    mutate(dateClsd = as.Date(dateClsd, format = "%m/%d/%y")) 
library(tidyr)

# Reshaping data
long_data <- combined_data |>
  pivot_longer(cols = starts_with("date"), 
               names_to = "phase", 
               values_to = "date")


# Convert phase names
long_data$phase <- sub("date_of_", "", long_data$phase)

Creating offense categories

library(dplyr)
library(stringr)

long_data <- long_data |>
  mutate(
    offense = case_when(
      str_detect(offenseType, "DUI #2 - INFLUENCE|DUI #1 - INFLUENCE|DUI #1 - DRUG OR BOTH|DUI #1 - INFLUENCE, LEAVING SCENE OF CRASH - PROPERTY DAMAGE|VEHICLE OPERATION - LICENSE SUSPENDED  #1 FOR DUI|DUI #1 > LEGAL LIMIT|VEHICLE OPERATION - LICENSE SUSPENDED #2 FOR DUI") ~ "DUI and Related Offenses",
      
      str_detect(offenseType, "ASSAULT - SIMPLE|VIOLATION OF ABUSE PREVENTION ORDER|ASSAULT - SIMPLE, VIOLATION OF CONDITIONS OF RELEASE|AGGRAVATED ASSAULT ON A LAW ENFORCEMENT OFFICER - THREATEN WITH DEADLY WEAPON,  SIMPLE ASSAULT ON A PROTECTED PROFESSIONAL - BODILY INJURY") ~ "Assault and Abuse Violations",
      
       str_detect(offenseType, "RECKLESS ENDANGERMENT|VEHICLE OPERATION - RECKLESS OR GROSS NEGLIGENCE - #1|VEHICLE OPERATION - EXCESSIVE SPEED|VEHICLE OPERATION - CARELESS OR NEGLIGENT|LEAVING SCENE OF CRASH - PROPERTY DAMAGE") ~ "Reckless and Negligent Behavior",
      
       str_detect(offenseType, "UNLAWFUL TRESPASS - RESIDENCE/OCCUPIED|UNLAWFUL TRESPASS - LAND") ~ "Tresspassing",
       str_detect(offenseType, "DISORDERLY CONDUCT- FIGHT ETC") ~ "Disorderly Conduct",
      
       str_detect(offenseType, "VIOLATION OF CONDITIONS OF RELEASE|VEHICLE OPERATION - LICENSE SUSPENDED/OSC|VEHICLE OPERATION - LICENSE SUSPENDED") ~ "Violation of Legal Order",

            is.na(offenseType) | offenseType == "" ~ "Unknown", # Handles NA and empty strings
      TRUE ~ "Theft and Property-Related Crimes"  
    )
  )

install ggrepel

library(ggplot2)
library(gganimate)
library(dplyr)

library(ggrepel)


# set of phases for each person
df <- long_data %>%
  complete(lastName, nesting(Program, offense), phase = c("dateIncident", "dateRef", "dateIntake", "dateClsd"))

# Arrange by offender_name and date, then fill forward the dates within each offender group

df <- df %>%
  filter(date >= as.Date("2023-01-01"))|>
  arrange(lastName, date) %>%
  group_by(lastName) %>%
  fill(date, .direction = "down") %>%
  ungroup()

df$phase <- factor(df$phase, levels = c("dateIncident", "dateRef", "dateIntake", "dateClsd"))


# Create the plot
p <- ggplot(df, aes(x = phase, y = Program, group = lastName, color = offense)) +
  geom_jitter(aes(size = !is.na(date))) +

  
  labs(title = 'Date: {frame_along}', x = 'Phase', y = 'Program Name') +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_color_brewer(palette = "Set1") +
  transition_states(states = phase, transition_length = 20, state_length = 10) +
  transition_time(date) +
  guides(size = 'none')  # Hide the size legend 

# Create the animation
anim <- p + 
  transition_reveal(along = date) +
  ease_aes('linear')

# Save the animation
anim_save("restorative_justice_animation.gif", animation = anim, fps = 10)
## Warning: Using size for a discrete variable is not advised.
anim 
## Warning: Using size for a discrete variable is not advised.