-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSTA313 Draft.Rmd
386 lines (273 loc) · 11.7 KB
/
STA313 Draft.Rmd
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
---
title: "STA313 Final"
author: "Eric Yin"
date: "`r Sys.Date()`"
output: html_document
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(tidyverse)
```
```{r}
kaggle_raw <- read.csv("US Mass Shooting 1966-2019 (cleaned).csv")
mj_raw <- read.csv("Mother Jones - Mass Shootings Database, 1982 - 2022 - Sheet1.csv")
##functions
#defined function just to make column splitting easier
reassign <- function(column, final) {
temp <- c()
for (i in 1:length(column)){
temp <- append(temp, column[[i]][final])
}
return(temp)
}
#defined function to change a repeated typo
change <- function(column, typo, correction){
temp <- c()
for (i in 1:length(column)){
if(identical(column[i],typo)){
temp <- append(temp, correction)
} else {
temp <- append(temp, column[i])
}
}
return(temp)
}
##creating date columns
#create month label
kaggle_raw <- kaggle_raw %>% mutate(Month = str_split(Date, "/"))
kaggle_raw$Month <- reassign(kaggle_raw$Month, 1)
kaggle_raw <- kaggle_raw %>% mutate(Month = as.numeric(Month))
#confirms no weird categories plus sums to total observations
# kaggle_raw %>% group_by(Month) %>% summarize(n= n())
# sum((kaggle_raw %>% group_by(Month) %>% summarize(n= n()))$n)
#create year label
kaggle_raw <- kaggle_raw %>% mutate(Year = str_split(Date, "/"))
kaggle_raw$Year <- reassign(kaggle_raw$Year, 3)
kaggle_raw <- kaggle_raw %>% mutate(Year = case_when(Year > 19 ~ paste0("19", as.character(Year)), TRUE ~ paste0("20", as.character(Year)))) %>% mutate(Year = as.numeric(Year))
#confirms no weird categories plus sums to total observations
# kaggle_raw %>% group_by(Year) %>% summarize(n= n()) %>% arrange(desc(Year)) %>% print(n = 50)
# sum((kaggle_raw %>% group_by(Year) %>% summarize(n= n()))$n)
#create day label
kaggle_raw <- kaggle_raw %>% mutate(Day = str_split(Date, "/"))
kaggle_raw$Day <- reassign(kaggle_raw$Day, 2)
kaggle_raw <- kaggle_raw %>% mutate(Day = as.numeric(Day))
#confirms no weird categories plus sums to total observations
# kaggle_raw %>% group_by(Day) %>% summarize(n= n()) %>% arrange(desc(Day)) %>% print(n = 50)
# sum((kaggle_raw %>% group_by(Day) %>% summarize(n= n()))$n)
## same for mj
#create month label
mj_raw <- mj_raw %>% mutate(Month = str_split(date, "/"))
mj_raw$Month <- reassign(mj_raw$Month, 1)
mj_raw <- mj_raw %>% mutate(Month = as.numeric(Month))
#confirms no weird categories plus sums to total observations
# mj_raw %>% group_by(Month) %>% summarize(n= n())
# sum((mj_raw %>% group_by(Month) %>% summarize(n= n()))$n)
#create day label
mj_raw <- mj_raw %>% mutate(Day = str_split(date, "/"))
mj_raw$Day <- reassign(mj_raw$Day, 2)
mj_raw <- mj_raw %>% mutate(Day = as.numeric(Day))
# #confirms no weird categories plus sums to total observations
# mj_raw %>% group_by(Day) %>% summarize(n= n()) %>% arrange(desc(Day)) %>% print(n = 50)
# sum((mj_raw %>% group_by(Day) %>% summarize(n= n()))$n)
#this one is duplicated with slightly different locations
mj_raw <- mj_raw %>% filter(location != "Parkland, Washington")
##merging data
#add columns in from mj
newnames <- c("MJ.Summary", "Prior.MH", "MH.Details", "Legal.Weapons", "Obtained.Where", "Weapon.Type", "Weapon.Details", "Main.Source", "MH.Source", "Extra.Source", "Shooting.Type")
oldnames <- c("summary", "prior_signs_mental_health_issues", "mental_health_details", "weapons_obtained_legally", "where_obtained", "weapon_type", "weapon_details", "sources", "mental_health_sources", "sources_additional_age", "type")
#select new columns that we need, plus rearrange them
mj_raw <- mj_raw %>% dplyr::select(location, year, Month, Day, all_of(oldnames))
colnames(mj_raw) <- c("Location", "Year", "Month", "Day", newnames)
#join data
joined_data <- left_join(kaggle_raw, mj_raw, by = c("Location", "Year", "Month", "Day"))
#dataset manipulation
#create state variable
data <- joined_data %>% mutate(State = str_trim(reassign(str_split(joined_data$Location, ", "), 2))) %>% mutate(State = change(State, "CA", "California") %>% change("NV", "Nevada") %>% change("Lousiana", "Louisiana") %>% change("San Diego", "California") %>% change("Souderton", "Pennsylvania")) %>% mutate(State = case_when(is.na(State) ~ "Washington", TRUE ~ State))
#clean Cause
data <- data %>% mutate(Cause = str_to_title(Cause)) %>% mutate(Cause = case_when(Cause == "-999" ~ "Unknown",
Cause %in% c("Breakup", "Domestic Disputer", "Domestic Dispute") ~ "Domestic",
Cause %in% c("Anger", "Fight", "Argue", "Assaulting", "Business Dispute", "Fight", "Frustration", "Neighbors Conflict", "Revenge") ~ "Anger",
Cause %in% c("Suspension", "Unemployment", "Failing Exams") ~ "Employment/School Related",
Cause %in% c("Drunk", "Fun", "Robbery") ~ "Other",
Cause %in% c("Racism", "Religious Radicalism") ~ "Religion/Race Related",
TRUE ~ Cause))
#clean weapon types
# data <- data %>% mutate(Handgun = grepl("handgun", str_to_lower(Weapon.Type)) | grepl("pistol", str_to_lower(Weapon.Type)) | grepl("revolver", str_to_lower(Weapon.Type)), Rifle = grepl("rifle", str_to_lower(Weapon.Type)), Shotgun = grepl("shotgun", str_to_lower(Weapon.Type)))
data <- data %>% mutate(Weapon.Type = case_when(
is.na(Weapon.Type) ~ "Unknown",
TRUE ~ Weapon.Type
))
#check listings
# data %>% group_by(State) %>% summarize(n = n()) %>% arrange(State) %>% print(n = 50)
#confirm no data was lost
# nrow(data)
# sum((data %>% group_by(State) %>% summarize(n = n()))$n)
write.csv(data,file='STA313_Final_Project/finaldata_313.csv', row.names=FALSE)
```
```{r}
class(data$Year)
max = 2019
min = 1966
response = "Fatalities"
temp <- data %>% filter(Year < max) %>% filter(Year > min)
feds <- read.csv("STA313_Final_Project/federal_laws.csv")
t <- temp %>% group_by(Year) %>% summarize(n = n())
x <- tibble(Year = c(1969:2019), count = rep(0, 51))
y <- left_join(x, t, by = c("Year")) %>% mutate(n = case_when(is.na(n) ~ 0, TRUE ~ as.numeric(as.character(n))))
product <- temp %>% group_by(Year) %>%
summarise(count = sum(Fatalities)) %>%
ggplot(aes(x = Year, y = count)) + geom_line()
product_laws <- geom_point(data = (temp %>% filter(Year %in% feds$Year_Implemented) %>% group_by(Year) %>% summarise(count = sum(Fatalities))), aes(x = Year, y = count))
product + product_laws + geom_label()
```
```{r}
policies <- read.csv("../policies.csv")
p <- policies%>% filter(Year < 1981, Type == "background check") %>% mutate(X1 = str_split(X1, "\n"), X2 = str_split(X2, "\n"), X3 = str_split(X3, "\n"), X4 = str_split(X4, "\n"))
final_list <- list()
bc <- c("X2")
for(i in nrow(p)){
p2 <- p %>% select(all_of(bc))
tlist <- list()
for(j in 1:length(bc)){
tlist[[length(tlist) + 1]] <- p2[,j][[1]]
}
final_list[[length(final_list) + 1]] <- Reduce(intersect, tlist)
}
Reduce(intersect, final_list)
df1 <-
ggplot() + geom_line(aes(x = 1:10, y = 1:10)) + geom_line(aes(x = 1:10, y = -1:-10))
```
# CODE FOR GGPLOT
```{r}
# this is for incidents by year
temp_data %>% mutate(Year <- as.numeric(Year)) %>%
group_by(Year) %>%
summarise(count = n()) %>%
ggplot(aes(x = Year, y = count, group=1)) +
geom_line(stat = "identity")
# fatalities per year
temp_data %>% mutate(Year <- as.numeric(Year),
Fatalities <- as.numeric(Fatalities)) %>%
group_by(Year, Fatalities) %>%
summarise(count = n()) %>%
ggplot(aes(x = Year, y = Fatalities, group=1)) +
geom_line(stat = "identity")
# injured per year
temp_data %>% mutate(Year <- as.numeric(Year),
Injured <- as.numeric(Injured)) %>%
group_by(Year, Injured) %>%
summarise(count = n()) %>%
ggplot(aes(x = Year, y = Injured, group=1)) +
geom_line(stat = "identity")
#victims per year
temp_data %>% mutate(Year <- as.numeric(Year),
Total.victims <- as.numeric(Total.victims)) %>%
group_by(Year, Total.victims) %>%
summarise(count = n()) %>%
ggplot(aes(x = Year, y = Total.victims, group=1)) +
geom_line(stat = "identity")
# Group by State
temp_data %>% mutate(Year <- as.numeric(Year)) %>%
group_by(Year, State) %>%
summarise(count = n()) %>%
ggplot(aes(x = Year, y = count, fill = factor(State))) +
geom_bar(stat = "identity", position = "fill")
```
This R Markdown document is made interactive using Shiny. Unlike the more traditional workflow of creating static reports, you can now create documents that allow your readers to change the assumptions underlying your analysis and see the results immediately.
Hi
To learn more, see [Interactive Documents](http://rmarkdown.rstudio.com/authoring_shiny.html).
## Inputs and Outputs
You can embed Shiny inputs and outputs in your document. Outputs are automatically updated whenever inputs change. This demonstrates how a standard R plot can be made interactive by wrapping it in the Shiny `renderPlot` function. The `selectInput` and `sliderInput` functions create the input widgets used to drive the plot.
```{r eruptions, echo=FALSE}
library(shiny)
library(dplyr)
library(ggplot2)
```
# Define UI for app that draws a histogram ----
```{r eruptions, echo=FALSE}
ui <- fluidPage(
data <- read.csv("finaldata_313.csv"),
# App title ----
titlePanel("Us mass shooting"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of bins ----
sliderInput(inputId = "bins",
label = "Dates:",
min = as.Date("1966-01-01","%Y-%m-%d"),
max = as.Date("2019-12-31","%Y-%m-%d"),
value=as.Date("2016-12-01"),timeFormat="%Y-%m-%d")
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Histogram ----
plotOutput(outputId = "distPlot")
)
)
)
```
```{r}
shinyServer(function(input, output) {
output$trendPlot <- renderGraph({
bins <- input$bins
x <- temp_data$Year
min = as.Date("1966-01-01","%Y-%m-%d")
max = as.Date("2019-12-31","%Y-%m-%d")
trace1 <- list(x = x,
autobinx = FALSE,
xbins = list(start = min,
end = max,
size = ((max-min)/bins)
),
type = "histogram"
)
data <- list(trace1)
layout<- list(xaxis =
list(title = "Ratings",
range = c(min, max),
autorange = FALSE,
autotick = FALSE,
tick0 = min,
dtick = ((max-min)/bins)
)
)
return(list(
list(id = "trendPlot",
task = "newPlot",
data = data,
layout = layout
)
))
})
})
```
```{r eruptions, echo=FALSE}
# Define server logic required to draw a histogram ----
server <- function(input, output) {
# Histogram of the Old Faithful Geyser Data ----
# with requested number of bins
# This expression that generates a histogram is wrapped in a call
# to renderPlot to indicate that:
#
# 1. It is "reactive" and therefore should be automatically
# re-executed when inputs (input$bins) change
# 2. Its output type is a plot
output$distPlot <- renderPlot({
x <- temp_data$Year
bins <- seq(min(x), max(x), length.out = input$bins + 1)
temp_data %>% mutate(Year <- as.numeric(Year)) %>%
group_by(Year) %>%
summarise(count = n()) %>%
ggplot(aes(x = Year, y = count, group=1)) +
geom_line(stat = "identity")
})
}
```
```{r eruptions, echo=FALSE}
shinyApp(ui, server)
```