{"cells":[{"metadata":{},"cell_type":"markdown","source":"****NFL 1st and Future - Notebook****"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Libraries\nlibrary(tidyverse)\nlibrary(data.table)\nlibrary(ggplot2)\nlibrary(plotly)\nlibrary(RColorBrewer)\nlibrary(arules)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Read in Files\ninjury_record <- data.table::fread(\"../input/nfl-playing-surface-analytics/InjuryRecord.csv\", stringsAsFactors = F)\nplayer_tracking <- data.table::fread(\"../input/nfl-playing-surface-analytics/PlayerTrackData.csv\", stringsAsFactors = F)\nplay_list <- data.table::fread(\"../input/nfl-playing-surface-analytics/PlayList.csv\", stringsAsFactors = F)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Fixing Data - Stadium Type\noutdoor <- c('Outdoor', 'Outdoors', 'Cloudy', 'Heinz Field', \n             'Outdor', 'Ourdoor', 'Outside', 'Outddors', \n             'Outdoor Retr Roof-Open', 'Oudoor', 'Bowl')\n\nindoor_closed <- c('Indoors', 'Indoor', 'Indoor, Roof Closed', 'Indoor, Roof Closed',\n                   'Retractable Roof', 'Retr. Roof-Closed', 'Retr. Roof - Closed', 'Retr. Roof Closed')\n\nindoor_open <- c('Indoor, Open Roof', 'Open', 'Retr. Roof-Open', 'Retr. Roof - Open')\n\ndome_closed <- c('Dome', 'Domed, closed', 'Closed Dome', 'Domed', 'Dome, closed')\n\ndome_open <- c('Domed, Open', 'Domed, open')\n\nconvert_stadiums <- function(x) {\n  if(x %in% outdoor) {\n    \"outdoor\"\n  } else if(x %in% indoor_closed) {\n    \"indoor closed\"\n  } else if(x %in% indoor_open) {\n    \"indoor open\"\n  } else if(x %in% dome_closed) {\n    \"dome_closed\"\n  } else if( x %in% dome_open) {\n    \"dome_open\"\n  } else {\n    \"unknown\"\n  }\n  \n}    \n\nplay_list <- play_list %>% \n  mutate(StadiumType = mapply(convert_stadiums, StadiumType))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Fixing Data - Weather\nrain <- c('30% Chance of Rain', 'Rainy', 'Rain Chance 40%', 'Showers', 'Cloudy, 50% change of rain', 'Rain likely, temps in low 40s.',\n          'Cloudy with periods of rain, thunder possible. Winds shifting to WNW, 10-20 mph.',\n          'Scattered Showers', 'Cloudy, Rain', 'Rain shower', 'Light Rain', 'Rain')\n\novercast <- c('Party Cloudy', 'Cloudy, chance of rain',\n              'Coudy', \n              'Cloudy and cold', 'Cloudy, fog started developing in 2nd quarter',\n              'Partly Clouidy', 'Mostly Coudy', 'Cloudy and Cool',\n              'cloudy', 'Partly cloudy', 'Overcast', 'Hazy', 'Mostly cloudy', 'Mostly Cloudy',\n              'Partly Cloudy', 'Cloudy')\n\nclear <- c('Partly clear', 'Sunny and clear', 'Sun & clouds', 'Clear and Sunny',\n           'Sunny and cold', 'Sunny Skies', 'Clear and Cool', 'Clear and sunny',\n           'Sunny, highs to upper 80s', 'Mostly Sunny Skies', 'Cold',\n           'Clear and warm', 'Sunny and warm', 'Clear and cold', 'Mostly sunny',\n           'T: 51; H: 55; W: NW 10 mph', 'Clear Skies', 'Clear skies', 'Partly sunny',\n           'Fair', 'Partly Sunny', 'Mostly Sunny', 'Clear', 'Sunny')\n\nsnow <- c('Cloudy, light snow accumulating 1-3\"', 'Heavy lake effect snow', 'Snow')\n\nnone <- c('N/A Indoor', 'Indoors', 'Indoor', 'N/A (Indoors)', 'Controlled Climate')\n\nconvert_weather <- function(x) {\n  if(x %in% rain) {\n    \"rain\"\n  } else if(x %in% overcast) {\n    \"overcast\"\n  } else if(x %in% clear) {\n    \"clear\"\n  } else if(x %in% snow) {\n    \"snow\"\n  } else if( x %in% none) {\n    \"indoors\"\n  } else {\n    \"unknown\"\n  }\n  \n}    \n\nplay_list <- play_list %>% \n  mutate(Weather = mapply(convert_weather, Weather))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"****Key Variables Graphs****"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injury Types\ninjury_types <- data.frame(prop.table(table(injury_record$BodyPart)))\ninjury_types <- injury_types %>%\n  mutate(Freq = round(Freq * 100, 2)) %>%\n  arrange(desc(Freq))\ninjury_types$Var1 <- factor(injury_types$Var1, levels = injury_types$Var1)\nplot_ly(injury_types, x = ~Var1, y = ~Freq, text = ~paste0(Freq, '%'), textposition = 'auto', type = 'bar') %>%\n  layout(title = 'NFL Injuries By Body Part',\n         xaxis = list(title = 'Body Part'),\n         yaxis = list(title = 'Frequency', ticksuffix = \"%\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injuries By Field Type\ninjury_field <- data.frame(prop.table(table(injury_record$Surface)))\ninjury_field <- injury_field %>%\n  mutate(Freq = round(Freq * 100, 2)) %>%\n  arrange(desc(Freq))\ninjury_field$Var1 <- factor(injury_field$Var1, levels = injury_field$Var1)\nplot_ly(injury_field, x = ~Var1, y = ~Freq, text = ~paste0(Freq, '%'), textposition = 'auto', type = 'bar') %>%\n  layout(title = 'NFL Injuries By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Frequency', ticksuffix = \"%\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Pct Field Type\nfield <- play_list[,c(2,8)]\nfield <- field[!duplicated(field),]\nfield <- data.frame(prop.table(table(field$FieldType)))\nfield <- field %>%\n  mutate(Freq = round(Freq * 100, 2)) %>%\n  arrange(desc(Freq))\nfield$Var1 <- factor(field$Var1, levels = field$Var1)\nplot_ly(field, x = ~Var1, y = ~Freq, text = ~paste0(Freq, '%'), textposition = 'auto', type = 'bar') %>%\n  layout(title = 'NFL Field Surfaces',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Frequency', ticksuffix = \"%\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Pct Plays Injured Per Field Type\nplay_list <- play_list %>% \n  mutate(IsInjured = GameID %in% injury_record$GameID)\ninjury_pct <- play_list %>% \n  distinct(GameID, FieldType, IsInjured) %>% \n  group_by(FieldType, IsInjured) %>% \n  summarise(n = n()) %>%\n  mutate(Pct_Injured = round((n / sum(n) * 100), 2)) %>%\n  filter(IsInjured == T)\n\navg_injury <- mean(injury_pct$Pct_Injured)\n\nhline <- function(y = 0, color = \"red\") {\n  list(\n    type = \"line\", \n    x0 = 0, \n    x1 = 1, \n    xref = \"paper\",\n    y0 = y, \n    y1 = y, \n    line = list(color = color)\n  )\n}\n\nplot_ly(injury_pct, x = ~FieldType, y = ~Pct_Injured, text = ~paste0(Pct_Injured, '%'), textposition = 'auto', type = 'bar') %>%\n  layout(title = 'NFL Injury Percentage by Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Pct Injured',\n                      showticklabels = FALSE),\n         shapes = list(hline(avg_injury))) %>%\n  add_annotations(\n    x=-0.5,\n    y=avg_injury + 0.1,\n    xref = \"x\",\n    yref = \"y\",\n    text = \"Average Injury Percentage - 1.89%\",\n    xanchor = 'left',\n    showarrow = F\n  )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injuries By Roster Position\nposition <- play_list[,c(1,4)]\nposition <- position[!duplicated(position),]\ninjury_position <- merge(injury_record, position, by = 'PlayerKey')\ninjury_position <- data.frame(prop.table(table(injury_position$RosterPosition)))\ninjury_position <- injury_position %>%\n  mutate(Freq = round(Freq * 100, 2)) %>%\n  arrange(Freq)\ninjury_position$Var1 <- factor(injury_position$Var1, levels = injury_position$Var1)\nplot_ly(injury_position, x = ~Freq, y = ~Var1, text = ~paste0(Freq, '%'), textposition = 'auto', type = 'bar', orientation = 'h') %>%\n  layout(title = 'NFL Injuries By Roster Position',\n         xaxis = list(title = 'Frequency', ticksuffix = \"%\"),\n         yaxis = list(title = 'Roster Position'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Pct Position\nposition <- play_list[,c(2,4)]\nposition <- position[!duplicated(position),]\nposition <- data.frame(prop.table(table(position$RosterPosition)))\nposition <- position %>%\n  mutate(Freq = round(Freq * 100, 2)) %>%\n  arrange(Freq)\nposition$Var1 <- factor(position$Var1, levels = position$Var1)\nplot_ly(position, x = ~Freq, y = ~Var1, text = ~paste0(Freq, '%'), textposition = 'auto', type = 'bar', orientation = 'h') %>%\n  layout(title = 'NFL Roster Positions',\n         xaxis = list(title = 'Frequency', ticksuffix = \"%\"),\n         yaxis = list(title = 'Roster Position'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injuries By Stadium Type\nstadium <- play_list[,c(1:2,7)]\nstadium <- stadium[!duplicated(stadium),]\ninjury_stadium <- merge(injury_record, stadium, by = c('PlayerKey', 'GameID'))\ninjury_stadium <- data.frame(prop.table(table(injury_stadium$StadiumType)))\ninjury_stadium <- injury_stadium %>%\n  mutate(Freq = round(Freq * 100, 2)) %>%\n  arrange(Freq)\ninjury_stadium$Var1 <- factor(injury_stadium$Var1, levels = injury_stadium$Var1)\nplot_ly(injury_stadium, x = ~Freq, y = ~Var1, text = ~paste0(Freq, '%'), textposition = c('outside', 'outside', 'outside', 'inside', 'inside'), type = 'bar', orientation = 'h') %>%\n  layout(title = 'NFL Injuries By Stadium Type',\n         xaxis = list(title = 'Frequency', ticksuffix = \"%\"),\n         yaxis = list(title = 'Stadium Type'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Pct Stadium\nstadium <- play_list[,c(2,7)]\nstadium <- stadium[!duplicated(stadium),]\nstadium <- data.frame(prop.table(table(stadium$StadiumType)))\nstadium <- stadium %>%\n  mutate(Freq = round(Freq * 100, 2)) %>%\n  arrange(Freq)\nstadium$Var1 <- factor(stadium$Var1, levels = stadium$Var1)\nplot_ly(stadium, x = ~Freq, y = ~Var1, text = ~paste0(Freq, '%'), textposition = 'auto', type = 'bar', orientation = 'h') %>%\n  layout(title = 'NFL Stadium Types',\n         xaxis = list(title = 'Frequency', ticksuffix = \"%\"),\n         yaxis = list(title = 'Stadium Type'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injuries By Weather\nweather <- play_list[,c(1:2,10)]\nweather <- weather[!duplicated(weather),]\ninjury_weather <- merge(injury_record, weather, by = c('PlayerKey', 'GameID'))\ninjury_weather <- data.frame(prop.table(table(injury_weather$Weather)))\ninjury_weather <- injury_weather %>%\n  mutate(Freq = round(Freq * 100, 2)) %>%\n  arrange(Freq)\ninjury_weather$Var1 <- factor(injury_weather$Var1, levels = injury_weather$Var1)\nplot_ly(injury_weather, x = ~Freq, y = ~Var1, text = ~paste0(Freq, '%'), textposition = 'auto', type = 'bar', orientation = 'h') %>%\n  layout(title = 'NFL Injuries By Weather',\n         xaxis = list(title = 'Frequency', ticksuffix = \"%\"),\n         yaxis = list(title = 'Weather'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Pct Weather\nweather <- play_list[,c(2,10)]\nweather <- weather[!duplicated(weather),]\nweather <- data.frame(prop.table(table(weather$Weather)))\nweather <- weather %>%\n  mutate(Freq = round(Freq * 100, 2)) %>%\n  arrange(Freq)\nweather$Var1 <- factor(weather$Var1, levels = weather$Var1)\nplot_ly(weather, x = ~Freq, y = ~Var1, text = ~paste0(Freq, '%'), textposition = 'auto', type = 'bar', orientation = 'h') %>%\n  layout(title = 'NFL Weather Occurences',\n         xaxis = list(title = 'Frequency', ticksuffix = \"%\"),\n         yaxis = list(title = 'Weather'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injuries By Play Type\nplay_type <- play_list[,c(1:2,11)]\nplay_type <- play_type[!duplicated(play_type),]\nplay_type$PlayType <- ifelse(play_type$PlayType == '' | play_type$PlayType == 0, 'Unknown', play_type$PlayType)\ninjury_play_type <- merge(injury_record, play_type, by = c('PlayerKey', 'GameID'))\ninjury_play_type <- data.frame(prop.table(table(injury_play_type$PlayType)))\ninjury_play_type <- injury_play_type %>%\n  mutate(Freq = round(Freq * 100, 2)) %>%\n  arrange(Freq)\ninjury_play_type$Var1 <- factor(injury_play_type$Var1, levels = injury_play_type$Var1)\nplot_ly(injury_play_type, x = ~Freq, y = ~Var1, text = ~paste0(Freq, '%'), textposition = 'auto', type = 'bar', orientation = 'h') %>%\n  layout(title = 'NFL Injuries By Play Type',\n         xaxis = list(title = 'Frequency', ticksuffix = \"%\"),\n         yaxis = list(title = 'Play Type'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Pct Play Type\nplay_type <- play_list[,c(2,11)]\nplay_type <- play_type[!duplicated(play_type),]\nplay_type$PlayType <- ifelse(play_type$PlayType == '' | play_type$PlayType == 0, 'Unknown', play_type$PlayType)\nplay_type <- data.frame(prop.table(table(play_type$PlayType)))\nplay_type <- play_type %>%\n  mutate(Freq = round(Freq * 100, 2)) %>%\n  arrange(Freq)\nplay_type$Var1 <- factor(play_type$Var1, levels = play_type$Var1)\nplot_ly(play_type, x = ~Freq, y = ~Var1, text = ~paste0(Freq, '%'), textposition = 'auto', type = 'bar', orientation = 'h') %>%\n  layout(title = 'NFL Play Types',\n         xaxis = list(title = 'Frequency', ticksuffix = \"%\"),\n         yaxis = list(title = 'Play Type'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injuries By Player Game Number\nplay_game <- play_list[,c(1:2,6)]\nplay_game <- play_game[!duplicated(play_game),]\ninjury_play_game <- merge(injury_record, play_game, by = c('PlayerKey', 'GameID'))\ninjury_play_game <- data.frame(table(injury_play_game$PlayerGame))\n\nplot_ly(injury_play_game, x = ~as.numeric(Var1), y = ~Freq, type = 'scatter', mode = 'lines+markers') %>%\n  layout(title = 'NFL Injuries By Game Number',\n         xaxis = list(title = 'Game Number'),\n         yaxis = list(title = 'Total Injured'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injuries Survival Bias\ntotal_players <- play_list %>%\n  group_by(PlayerGame) %>%\n  summarise(num_players = n_distinct(PlayerKey))\n\nplot_ly(total_players, x = ~as.numeric(PlayerGame), y = ~num_players, type = 'scatter', mode = 'lines+markers') %>%\n  layout(title = 'NFL Total Players By Week',\n         xaxis = list(title = 'Game Number'),\n         yaxis = list(title = 'Total Players'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injuries By Play Number + Field Type\nplay_number <- play_list[,c(1:3,8,12)]\nplay_number <- play_number[!duplicated(play_number),]\ninjury_play_number <- merge(injury_record, play_number, by = c('PlayerKey', 'GameID', 'PlayKey'))\n\ninjury_play_number <- injury_play_number %>% group_by(PlayerGamePlay, FieldType) %>% summarise(Freq = n())\n\nplot_ly(injury_play_number, y = ~PlayerGamePlay, color = ~FieldType, colors = c(\"#132B43\", \"#56B1F7\"), type = 'box') %>%\n  layout(title = 'NFL Injuries By Play Number',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Play Number'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injury Days Out\ninjury_record$DaysOut <- as.factor(ifelse(injury_record$DM_M42 == 1, 42, \n                                ifelse(injury_record$DM_M28 == 1, 28,\n                                       ifelse(injury_record$DM_M7 == 1, 7,\n                                              ifelse(injury_record$DM_M1 == 1, 1, 0)))))\n\ninjury_days_out <- data.frame(table(injury_record$DaysOut))\n\nplot_ly(injury_days_out, x = ~Var1, y = ~Freq, text = ~Freq, textposition = 'auto', type = 'bar') %>%\n  layout(title = 'NFL Injury Lengths',\n         xaxis = list(title = 'Injury Length'),\n         yaxis = list(title = 'Total Injured'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injury Days Out by Field Surface\ninjury_days_out_field <- injury_record %>% group_by(Surface) %>% mutate(Total = n()) %>%\n  group_by(DaysOut, Surface, Total) %>% summarise(Freq = n()/mean(Total))\n\nplot_ly(data = injury_days_out_field, x = ~Surface, y = ~Freq, color= ~DaysOut, type = 'bar')%>%\n  layout(title = 'NFL Injury Length By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Frequency', tickformat = '%'),\n         barmode = 'stack')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injury Days Out by Location\ninjury_days_out_loc <- injury_record %>% group_by(BodyPart) %>% mutate(Total = n()) %>%\n  group_by(DaysOut, BodyPart, Total) %>% summarise(Freq = n()/mean(Total))\n\nplot_ly(data = injury_days_out_loc, x = ~BodyPart, y = ~Freq, color= ~DaysOut, type = 'bar')%>%\n  layout(title = 'NFL Injury Length By Body Part',\n         xaxis = list(title = 'Body Part'),\n         yaxis = list(title = 'Frequency', tickformat = '%'),\n         barmode = 'stack')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injury Location by Field Surface\ninjury_loc_field <- injury_record %>% group_by(Surface) %>% mutate(Total = n()) %>%\n  group_by(BodyPart, Surface, Total) %>% summarise(Freq = n()/mean(Total))\n\nplot_ly(data = injury_loc_field, x = ~Surface, y = ~Freq, color= ~BodyPart, type = 'bar')%>%\n  layout(title = 'NFL Injury Body Part by Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Frequency', tickformat = '%'),\n         barmode = 'stack')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injury Days Out by Position\nposition <- play_list[,c(1,4)]\nposition <- position[!duplicated(position),]\ninjury_position <- merge(injury_record, position, by = 'PlayerKey')\ninjury_length_pos <- injury_position %>% group_by(Surface) %>% mutate(Total = n()) %>%\n  group_by(RosterPosition, Surface, Total) %>% summarise(Freq = n()/mean(Total))\n\nplot_ly(data = injury_length_pos, x = ~Surface, y = ~Freq, color= ~RosterPosition, type = 'bar')%>%\n  layout(title = 'NFL Injury Roster Position by Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Frequency', tickformat = '%'),\n         barmode = 'stack')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"****Differences in Player Movement****"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Acceleration\nplayer_tracking$a <- NA\nplayer_tracking$a[-1] <- with(player_tracking, (s[-1]-s[-length(s)]) / (time[-1]-time[-length(time)]))\nplayer_tracking$a[which(player_tracking$time==0)] <- NA\n\n# Direction Change\nplayer_tracking$dir_change <- NA\nplayer_tracking$dir_change[-1] <- with(player_tracking, dir[-1]-dir[-length(dir)])\nplayer_tracking <- player_tracking[,dir:=NULL]\n\nplayer_tracking$dir_change[which(player_tracking$time==0)] <- NA\nplayer_tracking$dir_change[which(player_tracking$dir_change < (-180))] <- player_tracking$dir_change[which(player_tracking$dir_change < (-180))] + 360\nplayer_tracking$dir_change[which(player_tracking$dir_change > (+180))] <- player_tracking$dir_change[which(player_tracking$dir_change > (+180))] - 360\n\n# Orientation vs Direction: negative means facing left, positive means facing right\nplayer_tracking$o_dir <- player_tracking$o - player_tracking$dir\nplayer_tracking <- player_tracking[,o:=NULL]\n\nplayer_tracking$o_dir[which(player_tracking$o_dir<(-180))] <- player_tracking$o_dir[which(player_tracking$o_dir<(-180))]+360\nplayer_tracking$o_dir[which(player_tracking$o_dir>(+180))] <- player_tracking$o_dir[which(player_tracking$o_dir>(+180))]-360","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Grouped By Play - Absolute Value for Dir Change and O_Dir so all facing same way\ntracking_data <- player_tracking %>% \n  group_by(PlayKey) %>%\n  summarise(max_speed = max(s, na.rm = T), avg_speed = mean(s, na.rm = T), mid_speed = median(s, na.rm = T), s_05 = quantile(s, .05, na.rm = T), s_25 = quantile(s, .25, na.rm = T), s_75 = quantile(s, .75, na.rm = T), s_95 = quantile(s, .95, na.rm = T),\n            max_accel = max(a, na.rm = T), avg_accel = mean(a, na.rm = T), mid_accel = median(a, na.rm = T), a_05 = quantile(a, .05, na.rm = T), a_25 = quantile(a, .25, na.rm = T), a_75 = quantile(a, .75, na.rm = T), a_95 = quantile(a, .95, na.rm = T),\n            max_decel = abs(min(a, na.rm = T)),\n            total_dist = sum(dis, na.rm = T), avg_dist = mean(dis, na.rm = T),\n            max_dir_change = max(abs(dir_change), na.rm = T), avg_dir_change = mean(abs(dir_change), na.rm = T), mid_dir_change = median(abs(dir_change), na.rm = T), dir_change_05 = quantile(abs(dir_change), .05, na.rm = T), dir_change_25 = quantile(abs(dir_change), .25, na.rm = T), dir_change_75 = quantile(abs(dir_change), .75, na.rm = T), dir_change_95 = quantile(abs(dir_change), .95, na.rm = T),\n            max_o_dir = max(abs(o_dir), na.rm = T), avg_o_dir = mean(abs(o_dir), na.rm = T), mid_o_dir = median(abs(o_dir), na.rm = T), o_dir_05 = quantile(abs(o_dir), .05, na.rm = T), o_dir_25 = quantile(abs(o_dir), .25, na.rm = T), o_dir_75 = quantile(abs(o_dir), .75, na.rm = T), o_dir_95 = quantile(abs(o_dir), .95, na.rm = T))\n\ninjuries <- injury_record[,c(3,5,10)]\ntracking_data_injuries <- merge(tracking_data, injuries, by = 'PlayKey', all.x = T)\ntracking_data_injuries <- merge(tracking_data_injuries, play_list, by = 'PlayKey')\ntracking_data_injuries$injured <- ifelse(is.na(tracking_data_injuries$Surface), 0, 1)\ntracking_data_injuries$injured <- ifelse(tracking_data_injuries$injured == 0, 'Healthy', 'Injured')\n\ntracking_data_vars <- merge(tracking_data, play_list, by = 'PlayKey')\ntracking_data_vars_injuries <- merge(tracking_data_injuries, play_list, by = 'PlayKey')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Tracking By Surface\nplot_ly(tracking_data_vars %>% filter(max_accel < 12), y = ~max_accel, color = ~FieldType, colors = c(\"#132B43\", \"#56B1F7\"), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Acceleration By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Maximum Acceleration (y/s^2)'))\n\nplot_ly(tracking_data_vars %>% filter(max_decel < 12), y = ~max_decel, color = ~FieldType, colors = c(\"#132B43\", \"#56B1F7\"), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Deceleration By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Maximum Deceleration (y/s^2)'))\n\nplot_ly(tracking_data_vars %>% filter(max_speed < 20), y = ~max_speed, color = ~FieldType, colors = c(\"#132B43\", \"#56B1F7\"), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Speed By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Maximum Speed (y/s)'))\n\nplot_ly(tracking_data_vars, y = ~total_dist, color = ~FieldType, colors = c(\"#132B43\", \"#56B1F7\"), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Total Distance By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_vars, y = ~avg_dist, color = ~FieldType, colors = c(\"#132B43\", \"#56B1F7\"), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Distance By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_vars, y = ~max_dir_change, color = ~FieldType, colors = c(\"#132B43\", \"#56B1F7\"), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Direction Change\\nBy Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_vars, y = ~avg_dir_change, color = ~FieldType, colors = c(\"#132B43\", \"#56B1F7\"), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Direction Change\\nBy Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_vars, y = ~avg_o_dir, color = ~FieldType, colors = c(\"#132B43\", \"#56B1F7\"), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Orientation - Direction Difference\\nBy Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Direction Change (Degrees)'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Tracking By Stadium\nplot_ly(tracking_data_vars %>% filter(max_accel < 12), y = ~max_accel, color = ~StadiumType, colors = 'Dark2', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Acceleration By Stadium Type',\n         xaxis = list(title = 'Stadium Type'),\n         yaxis = list(title = 'Maximum Acceleration (y/s^2)'))\n\nplot_ly(tracking_data_vars %>% filter(max_decel < 12), y = ~max_decel, color = ~StadiumType, colors = 'Dark2', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Deceleration By Stadium Type',\n         xaxis = list(title = 'Stadium Type'),\n         yaxis = list(title = 'Maximum Deceleration (y/s^2)'))\n\nplot_ly(tracking_data_vars %>% filter(max_speed < 20), y = ~max_speed, color = ~StadiumType, colors = 'Dark2', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Speed By Stadium Type',\n         xaxis = list(title = 'Stadium Type'),\n         yaxis = list(title = 'Maximum Speed (y/s)'))\n\nplot_ly(tracking_data_vars, y = ~total_dist, color = ~StadiumType, colors = 'Dark2', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Total Distance By Stadium Type',\n         xaxis = list(title = 'Stadium Type'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_vars, y = ~avg_dist, color = ~StadiumType, colors = 'Dark2', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Distance By Stadium Type',\n         xaxis = list(title = 'Stadium Type'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_vars, y = ~max_dir_change, color = ~StadiumType, colors = 'Dark2', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Direction Change\\nBy Stadium Type',\n         xaxis = list(title = 'Stadium Type'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_vars, y = ~avg_dir_change, color = ~StadiumType, colors = 'Dark2', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Direction Change\\nBy Stadium Type',\n         xaxis = list(title = 'Stadium Type'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_vars, y = ~avg_o_dir, color = ~StadiumType, colors = 'Dark2', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Orientation - Direction Difference\\nBy Stadium Type',\n         xaxis = list(title = 'Stadium Type'),\n         yaxis = list(title = 'Direction Change (Degrees)'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Tracking By Weather\nplot_ly(tracking_data_vars %>% filter(max_accel < 12), y = ~max_accel, color = ~Weather, colors = 'Accent', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Acceleration By Weather',\n         xaxis = list(title = 'Weather'),\n         yaxis = list(title = 'Maximum Acceleration (y/s^2)'))\n\nplot_ly(tracking_data_vars %>% filter(max_decel < 12), y = ~max_decel, color = ~Weather, colors = 'Accent', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Deceleration By Weather',\n         xaxis = list(title = 'Weather'),\n         yaxis = list(title = 'Maximum Deceleration (y/s^2)'))\n\nplot_ly(tracking_data_vars %>% filter(max_speed < 20), y = ~max_speed, color = ~Weather, colors = 'Accent', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Speed By Weather',\n         xaxis = list(title = 'Weather'),\n         yaxis = list(title = 'Maximum Speed (y/s)'))\n\nplot_ly(tracking_data_vars, y = ~total_dist, color = ~Weather, colors = 'Accent', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Total Distance By Weather',\n         xaxis = list(title = 'Weather'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_vars, y = ~avg_dist, color = ~Weather, colors = 'Accent', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Distance By Weather',\n         xaxis = list(title = 'Weather'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_vars, y = ~max_dir_change, color = ~Weather, colors = 'Accent', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Direction Change\\nBy Weather',\n         xaxis = list(title = 'Weather'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_vars, y = ~avg_dir_change, color = ~Weather, colors = 'Accent', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Direction Change\\nBy Weather',\n         xaxis = list(title = 'Weather'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_vars, y = ~avg_o_dir, color = ~Weather, colors = 'Accent', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Orientation - Direction Difference\\nBy Weather',\n         xaxis = list(title = 'Weather'),\n         yaxis = list(title = 'Direction Change (Degrees)'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Tracking By Injury\nplot_ly(tracking_data_vars_injuries %>% filter(max_accel < 12), y = ~max_accel, color = ~injured, colors = c('dark green', 'dark red'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Acceleration By Injury',\n         xaxis = list(title = 'Injury'),\n         yaxis = list(title = 'Maximum Acceleration (y/s^2)'))\n\nplot_ly(tracking_data_vars_injuries %>% filter(max_decel < 12), y = ~max_decel, color = ~injured, colors = c('dark green', 'dark red'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Deceleration By Injury',\n         xaxis = list(title = 'Injury'),\n         yaxis = list(title = 'Maximum Deceleration (y/s^2)'))\n\nplot_ly(tracking_data_vars_injuries %>% filter(max_speed < 20), y = ~max_speed, color = ~injured, colors = c('dark green', 'dark red'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Speed By Injury',\n         xaxis = list(title = 'Injury'),\n         yaxis = list(title = 'Maximum Speed (y/s)'))\n\nplot_ly(tracking_data_vars_injuries, y = ~total_dist, color = ~injured, colors = c('dark green', 'dark red'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Total Distance By Injury',\n         xaxis = list(title = 'Injury'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_vars_injuries, y = ~avg_dist, color = ~injured, colors = c('dark green', 'dark red'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Distance By Injury',\n         xaxis = list(title = 'Injury'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_vars_injuries, y = ~max_dir_change, color = ~injured, colors = c('dark green', 'dark red'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Direction Change\\nBy Injury',\n         xaxis = list(title = 'Injury'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_vars_injuries, y = ~avg_dir_change, color = ~injured, colors = c('dark green', 'dark red'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Direction Change\\nBy Injury',\n         xaxis = list(title = 'Injury'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_vars_injuries, y = ~avg_o_dir, color = ~injured, colors = c('dark green', 'dark red'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Orientation - Direction Difference\\nBy Injury',\n         xaxis = list(title = 'Injury'),\n         yaxis = list(title = 'Direction Change (Degrees)'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injury Location\ntracking_data_injuries_grouped <- tracking_data_vars_injuries %>% filter(injured == 'Injured')\ntracking_data_injuries_grouped <- merge(tracking_data_injuries_grouped, injury_record, by = 'PlayKey')\ntracking_data_injuries_grouped <- tracking_data_injuries_grouped[!duplicated(tracking_data_injuries_grouped$PlayKey),]\n\nplot_ly(tracking_data_injuries_grouped %>% filter(max_accel < 12), y = ~max_accel, color = ~BodyPart, colors = 'Set1', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Acceleration By Body Part',\n         xaxis = list(title = 'Body Part'),\n         yaxis = list(title = 'Maximum Acceleration (y/s^2)'))\n\nplot_ly(tracking_data_injuries_grouped %>% filter(max_decel < 12), y = ~max_decel, color = ~BodyPart, colors = 'Set1', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Deceleration By Body Part',\n         xaxis = list(title = 'Body Part'),\n         yaxis = list(title = 'Maximum Deceleration (y/s^2)'))\n\nplot_ly(tracking_data_injuries_grouped %>% filter(max_speed < 20), y = ~max_speed, color = ~BodyPart, colors = 'Set1', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Speed By Body Part',\n         xaxis = list(title = 'Body Part'),\n         yaxis = list(title = 'Maximum Speed (y/s)'))\n\nplot_ly(tracking_data_injuries_grouped, y = ~total_dist, color = ~BodyPart, colors = 'Set1', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Total Distance By Body Part',\n         xaxis = list(title = 'Body Part'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_injuries_grouped, y = ~avg_dist, color = ~BodyPart, colors = 'Set1', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Distance By Body Part',\n         xaxis = list(title = 'Body Part'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_injuries_grouped, y = ~max_dir_change, color = ~BodyPart, colors = 'Set1', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Direction Change\\nBy Body Part',\n         xaxis = list(title = 'Body Part'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_injuries_grouped, y = ~avg_dir_change, color = ~BodyPart, colors = 'Set1', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Direction Change\\nBy Body Part',\n         xaxis = list(title = 'Body Part'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_injuries_grouped, y = ~avg_o_dir, color = ~BodyPart, colors = 'Set1', type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Orientation - Direction Difference\\nBy Body Part',\n         xaxis = list(title = 'Body Part'),\n         yaxis = list(title = 'Direction Change (Degrees)'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Injury Surface\nplot_ly(tracking_data_injuries_grouped %>% filter(max_accel < 12), y = ~max_accel, color = ~Surface.x, colors = c('purple', 'orange'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Acceleration By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Maximum Acceleration (y/s^2)'))\n\nplot_ly(tracking_data_injuries_grouped %>% filter(max_decel < 12), y = ~max_decel, color = ~Surface.x, colors = c('purple', 'orange'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Deceleration By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Maximum Deceleration (y/s^2)'))\n\nplot_ly(tracking_data_injuries_grouped %>% filter(max_speed < 20), y = ~max_speed, color = ~Surface.x, colors = c('purple', 'orange'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Speed By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Maximum Speed (y/s)'))\n\nplot_ly(tracking_data_injuries_grouped, y = ~total_dist, color = ~Surface.x, colors = c('purple', 'orange'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Total Distance By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_injuries_grouped, y = ~avg_dist, color = ~Surface.x, colors = c('purple', 'orange'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Distance By Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Distance (Yards)'))\n\nplot_ly(tracking_data_injuries_grouped, y = ~max_dir_change, color = ~Surface.x, colors = c('purple', 'orange'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Maximum Direction Change\\nBy Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_injuries_grouped, y = ~avg_dir_change, color = ~Surface.x, colors = c('purple', 'orange'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Direction Change\\nBy Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Direction Change (Degrees)'))\n\nplot_ly(tracking_data_injuries_grouped, y = ~avg_o_dir, color = ~Surface.x, colors = c('purple', 'orange'), type = 'box') %>%\n  layout(title = 'NFL Tracking Data Average Orientation - Direction Difference\\nBy Field Surface',\n         xaxis = list(title = 'Field Surface'),\n         yaxis = list(title = 'Direction Change (Degrees)'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Regression Analysis\nregression_df <- merge(tracking_data, play_list, by = 'PlayKey')\nregression_df <- merge(regression_df, injury_record, by = c('PlayKey', 'PlayerKey', 'GameID'), all.x = T)\nregression_df$Injured <- ifelse(is.na(regression_df$BodyPart), 0, 1)\n\nset.seed(123)\nreg_healthy <- regression_df %>% filter(Injured == 0)\nreg_injured <- regression_df %>% filter(Injured == 1)\ntrain_healthy <- reg_healthy[sample(nrow(reg_healthy), 150),]\ntrain_injured <- reg_injured[sample(nrow(reg_injured), 50),]\ntrain_df <- rbind(train_healthy, train_injured)\ntest_df <- regression_df %>% filter(!(PlayKey %in% train_df$PlayKey))\n\nmodel <- glm(Injured ~ \n               max_speed + avg_speed + max_accel + avg_accel + max_decel +\n               total_dist + avg_dist + max_dir_change + avg_dir_change +\n               max_o_dir + avg_o_dir,\n             data = train_df, family = 'binomial')\nsummary(model)\npred <- predict(model, test_df, type = 'response')\npred <- ifelse(pred > 0.5, 1, 0)\ntable(pred, test_df$Injured)\nmean(pred == test_df$Injured)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Association Rules Analysis\narules_df <- regression_df\narules_df <- arules_df[,c('RosterPosition', 'StadiumType', 'FieldType', 'Weather', 'PlayType', 'Injured', 'PlayerGame', 'PlayerGamePlay')]\narules_df$Injured <- as.factor(ifelse(arules_df$Injured == 0, 'Healthy', 'Injured'))\narules_df$RosterPosition <- as.factor(arules_df$RosterPosition)\narules_df$PlayerGame <- as.factor(arules_df$PlayerGame)\narules_df$StadiumType <- as.factor(arules_df$StadiumType)\narules_df$FieldType <- as.factor(arules_df$FieldType)\narules_df$Weather <- as.factor(arules_df$Weather)\narules_df$PlayType <- as.factor(arules_df$PlayType)\narules_df$PlayerGamePlay <- as.factor(arules_df$PlayerGamePlay)\n\narules_t <- as(arules_df, \"transactions\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Healthy Rules\nruleset <- apriori(arules_t,\n                   parameter = list(support = 0.005, confidence = 0.8),\n                   appearance = list(rhs = 'Injured=Healthy', default = 'lhs'))\ntoprules <- sort(ruleset, decreasing = TRUE, na.last = NA, by = 'support')\ninspect(head(toprules, 10))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"051d70d956493feee0c6d64651c6a088724dca2a","_execution_state":"idle","trusted":false},"cell_type":"code","source":"# Injured Rules\nruleset <- apriori(arules_t,\n                   parameter = list(support = 0.00001, confidence = 0.00001),\n                   appearance = list(rhs = 'Injured=Injured', default = 'lhs'))\ntoprules <- sort(ruleset, decreasing = TRUE, na.last = NA, by = 'support')\ninspect(head(toprules, 10))","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"R","language":"R","name":"ir"},"language_info":{"mimetype":"text/x-r-source","name":"R","pygments_lexer":"r","version":"3.4.2","file_extension":".r","codemirror_mode":"r"}},"nbformat":4,"nbformat_minor":1}