-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.R
More file actions
318 lines (241 loc) · 10.3 KB
/
app.R
File metadata and controls
318 lines (241 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(tidyverse)
library(readr)
library(lubridate)
library(rgdal)
library(jsonlite)
library(httr)
library(shinydashboard)
library(shinydashboardPlus)
library(data.table)
library(ggmap)
library(leaflet)
library(plotly)
library(DT)
#Get proper year
properyear <- function(x, year=1968){
m <- year(x) %% 100
year(x) <- ifelse(m >= year %% 100, 1900+m, 2000+m)
x
}
#Get data
lifers.load <- PA_DOC_Lifers_10_12_16_years <- read_csv("PA DOC Lifers-10.12.16-years.csv") %>%
mutate(`Date of Birth` = properyear(as.Date(`Date of Birth`,format = "%m/%d/%y"), year = year(now())),
`Committing Date` = properyear(as.Date(`Committing Date`, format = "%m/%d/%y"), year = year(now())),
`Age at time of commitment` = round(as.numeric(difftime(`Committing Date`, `Date of Birth`, unit="weeks"))/52.25),
`# of Years in Prison` = round(as.numeric(difftime(now(), `Committing Date`, unit="weeks"))/52.25),
`Current Age` = round(as.numeric(difftime(now(), `Date of Birth`, unit="weeks"))/52.25),
`Committing County` = str_to_title(`Committing County`),
`Year Committed` = year(`Committing Date`))
#round((`Committing Date` - `Date of Birth`)/365))
# mutate(`Years in Prison (as of today)` = year(now())-year(properyear(as.Date(`Committing Date`,format = "%m/%d/%y"), year = year(now()))))
# properyear(as.Date("12/31/68",format = "%m/%d/%y"), year = year(now()))
# properyear(mdy(lifers.load$`Date of Birth`[1]), year(today()))
# geography level: 050
aa_varcode <- "B01001B_002E" #Estimate!!Total!!Male
white_varcode <- "B01001A_002E"
key <- "db29ecc2d9ec905998b48dd3dafe73475ddfb106"
# https://api.census.gov/data/2016/acs/acs5?get=
# https://factfinder.census.gov/faces/tableservices/jsf/pages/productview.xhtml?pid=ACS_16_5YR_B02001&prodType=table
# url <- "https://api.census.gov/data/2016/acs/acs5?get=NAME,B01001B_001EA,&for=county:*&in=state:42"
# works <- "https://api.census.gov/data/2016/acs/acs5?get=NAME,B01001B_001E&for=county:*&in=state:42&key=db29ecc2d9ec905998b48dd3dafe73475ddfb106"
# B01001B_002E
male.aa.url <- paste0("https://api.census.gov/data/2016/acs/acs5?get=NAME,", input$race, "&for=county:*&in=state:42&key=db29ecc2d9ec905998b48dd3dafe73475ddfb106")
r <- GET(male.aa.url)
ls(r)
c <- content(x = r, as = "text")
typeof(c)
json <- gsub('NaN', 'NA', c, perl = TRUE)
df <- data.frame(jsonlite::fromJSON(json))
# function to make first row column names
header.true <- function(df) {
names(df) <- as.character(unlist(df[1,]))
df[-1,]
}
df <- header.true(df)
# Pull out County name without the word "County")
separate(df, "NAME", c("County Name","State"),sep = ",")
df$`County Short` <- word(df$`NAME`, 1)
# Sample Charts
offense_category <- lifers.load %>% group_by(`Offense Category`) %>% count(sort = T)
offense <- lifers.load %>% group_by(`Offense`) %>% count(sort = T)
race <- lifers.load %>% group_by(`Race`) %>% count(sort = T)
ggplot(data = lifers.load, aes(x = `Age at time of commitment`)) + geom_bar()
cut(lifers.load$`Age at time of commitment`, breaks = seq(from = 15, to = 80, by = 5), right = FALSE, labels = FALSE)
agebreaks <- c(5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,500)
agelabels <- c("5-9","10-14","15-19","20-24","25-29","30-34",
"35-39","40-44","45-49","50-54","55-59","60-64","65-69",
"70-74","75-79","80-84","85+")
lifers.load <- setDT(lifers.load)[ , `Current Age Group` := cut(lifers.load$`Current Age`,
breaks = agebreaks,
right = FALSE,
labels = agelabels)]
ggplot(lifers.load, aes(x = `Current Age Group`)) + geom_bar() + facet_grid(rows = vars(Race))
# count by county
all_lifers <- lifers.load %>%
group_by(`Committing County`) %>%
dplyr::count()
aa_lifers <- lifers.load %>%
filter(Race == "BLACK") %>%
group_by(`Committing County`) %>%
dplyr::count()
# total aa pop by county
df <- mutate(df, aapop = as.numeric(as.character(B01001B_002E)))
df %>%
group_by(`County Short`) %>%
summarize(sum(aapop))
# merge on county
df <- df %>%
left_join(aa_lifers,by = c("County Short" = "Committing County")) %>%
# dplyr::rename(`LIP Black` = `n`) %>%
left_join(all_lifers,by = c("County Short" = "Committing County")) #%>%
# dplyr::rename(`LIP All` = `n`)
df <- rename(df, `LIP Black` = `n.x`, `LIP All` = `n.y`, `AA Pop` = `aapop`) %>%
mutate(`% AA Males LIP` = round(`LIP Black`/`AA Pop`,4))
# prison
prisonpop <- lifers.load %>%
group_by(`Current Location`) %>%
count(sort = T)
# prison_latlon <- geocode(prisonpop$`Current Location`, output = "latlona")
# prison_latlon
# df <- data.frame(fromJSON(json)) %>%
# mutate(X1 = as.character(X1),
# X2 = as.character(X2),
# X3 = as.character(X3),
# X4 = as.character(X4))
sum(county_lifers$n)
# DATA CLEANING
# Color Palette
aa_pal <- colorNumeric("Reds",domain = df$`% AA Males LIP`, na.color = "white")
# load counties
counties.load <- readOGR("Pennsylvania County Boundaries.geojson",layer = "OGRGeoJSON")
View(counties.load@data)
# Define UI Elements
header <- dashboardHeader(title = "Pennsylvania Prisons Serving Life in Prison",
dropdownMenu(type = "notifications",
notificationItem(text = "",
icon = icon("users"))
),
dropdownMenu(type = "tasks", badgeStatus = "success",
taskItem(value = 10, color = "green",
text = "")
),
dropdownMenu(type = "messages",
messageItem(
from = "",
message = HTML(""),
icon = icon("exclamation-circle"))
)
)
sidebar <- dashboardSidebar(
sidebarMenu(
id = "tabs",
menuItem("Plot", icon = icon("bar-chart"), tabName = "plot"),
menuItem("Table", icon = icon("table"), tabName = "table"),
menuItem("Map", icon = icon("map-marker"), tabName = "map"),
sliderInput("yearInput",
"Committed Year:",
min = min(lifers.load$`Year Committed`, na.rm = T),
max = max(lifers.load$`Year Committed`, na.rm = T),
sep = '',
step = 1,
round = T,
dragRange = T,
value = c(min(lifers.load$`Year Committed`, na.rm = T), max(lifers.load$`Year Committed`, na.rm = T)))
,
# Year
selectInput(inputId = "raceInmate",
label = "Race of Inmate:",
multiple = TRUE,
choices = c("All",str_to_title(sort(unique(lifers.load$Race)))),
selected = "All"),
menuItem("BarChart", tabName = "scatter",badgeLabel = "new", badgeColor = "green")
)
)
body <- dashboardBody(tabItems(
tabItem("plot",
fluidRow(
inputPanel(selectInput("variable",
label = "Select Measure",
choices = c(names(select(lifers.load,`Age at time of commitment`:`Year Committed`))),
selectize = T,
multiple = F,
selected = "# of Years in Prison"),
checkboxInput("checkbox", "Show by race"))),
fluidRow(plotlyOutput("plot"))
)
,
tabItem("table",
fluidPage(
box(title = "Prisoners: Life", DT::dataTableOutput("table"), width = 12))),
tabItem("map",
fluidPage(
fluidRow(
box(
selectInput("racemap",
"Per Capita Life in Prison by Race",
choices = c("WHITE" = "B01001A_002E","BLACK" = "B01001B_002E")
)
),
fluidRow(
box(leafletOutput("leaflet") , width = 12)
)))
)))
ui <- dashboardPage(header, sidebar, body)
# Define server logic required to draw a histogram
server <- function(input, output) {
# initial reactive
liferInput <- reactive({
lifers <- lifers.load %>%
# Slider Filter
filter(`Year Committed` >= input$yearInput[1] & `Year Committed` <= input$yearInput[2])
if (!("All" %in% input$raceInmate)) {
lifers <- subset(lifers, Race %in% input$raceInmate)}
return(lifers)
})
output$table <- DT::renderDataTable({
dat <- liferInput()
datatable(dat[, !names(dat) %in% c("Last Name", "First Name","Mid Name")]
,options = list(scrollX = TRUE))
})
output$plot <- renderPlotly({
dat <- liferInput()
dat <- dat %>%
rename(chartvar = input$variable)
g <- ggplot(dat, aes(x = chartvar, fill = chartvar)) + geom_histogram()
if (input$checkbox)
{ggplotly(g + facet_grid(rows = vars(Race)))}
else
{ggplotly(g)}
})
#map
output$leaflet <- renderLeaflet({
counties.load@data <- counties.load@data %>%
inner_join(df, by= c("fips_count" = "county"))
counties.load %>%
leaflet() %>%
addProviderTiles("Stamen.Toner") %>%
setView(lat = 40.8766,
lng = -77.8367,
zoom = 7) %>%
addPolygons(weight = 1,
fillOpacity = 1,
color = ~aa_pal(`% AA Males LIP`),
label = ~paste0(round(`% AA Males LIP`*1000,1)," out of every 1,000 black males from ", `County Short`, " County are serving Life in Prison"),
highlight = highlightOptions(weight = 3, color = "gray", bringToFront = T))
prisons <- read_csv("Prison Locations.csv")
keytable <- data.frame(RACE = c("WHITE","BLACK"),key = c(white_varcode, aa_varcode))
# import geojson
# counties.load <- readOGR("https://data.pa.gov/resource/n96m-gp6j",layer = "OGRGeoJSON")
})
}
# Run the application
shinyApp(ui = ui, server = server)