{"cells":[{"metadata":{"_uuid":"051d70d956493feee0c6d64651c6a088724dca2a","_execution_state":"idle","trusted":true},"cell_type":"code","source":"\nlibrary(tidyr)\nlibrary(dplyr)\nlibrary(ggplot2)\nlibrary(mice)\nlibrary(MASS)\nlibrary(caret)\nlibrary(forcats)\nlibrary(lattice)\nlibrary(tidyverse) # metapackage with lots of helpful functions\n\n\n\nInjury <- read.csv(\"../input/nfl-playing-surface-analytics/InjuryRecord.csv\")\nTrackData <- read.csv(\"../input/nfl-playing-surface-analytics/PlayerTrackData.csv\")\nPlaylist <- read.csv(\"../input/nfl-playing-surface-analytics/PlayList.csv\")\n\n\n\n\n###----------------------------------------------------------------------------------###\n\n###------------------------### Data Cleaning ###-------------------------------------###\n\n\n### 1: Injury and Field type\n\nInjury %>%\n  count(Surface) %>%\n  ggplot(aes(x = Surface, y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  ylab(\"Amount\") +\n  ggtitle(\"Number of injuries per field type\")\n\n\nInjury %>%\n  count(BodyPart) %>%\n  ggplot(aes(x = BodyPart, y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  ylab(\"Amount\") +\n  ggtitle(\"Number of injuries per field type\")\n\n\n###--------------------------------------------------------------------------------------------\n\n### Injury, field type, conditions\n\n###--------------------------------------------------------------------------------------------\n\n\n# Check the Injury and Playlist dataframe\n\nglimpse(Injury)\nglimpse(Playlist)\n\n# Combine the Injury and Playlist dataframes into one\n# Thereafter, feature engineering of the weather variable in 2 different ways\n# The same for the Position and Playtype variable and stadiumtype\n\n\nIn_play_weatherclean <- Playlist %>%\n  left_join(Injury, by = c(\"GameID\", \"PlayerKey\", \"PlayKey\")) \n\nglimpse(In_play_weatherclean)\nlevels(In_play_weatherclean$Weather)\nlevels(In_play_weatherclean$StadiumType)\nlevels(In_play_weatherclean$Position)\nlevels(In_play_weatherclean$PlayType)\n\n\nIn_play_weatherclean %>%\n  filter(Weather == \"\") %>%\n  count(StadiumType)\n\nIn_play_weatherclean <- In_play_weatherclean %>%\n  mutate(Weather_group = as.factor(ifelse(Weather == \"Sunny, Windy\" | \n                                  Weather == \"Sunny, highs to upper 80s\" |\n                                  Weather == \"Sunny Skies\" |\n                                  Weather == \"Sunny and cold\" |\n                                  Weather == \"Sunny and warm\" |\n                                  Weather == \"Sunny and clear\" |\n                                  Weather == \"Sunny\" |\n                                  Weather == \"Sun & clouds\" |\n                                  Weather == \"Mostly sunny\" |\n                                  Weather == \"Mostly Sunny\" |\n                                  Weather == \"Mostly Sunny Skies\" |\n                                  Weather == \"Partly sunny\" |\n                                  Weather == \"Partly Sunny\" |\n                                  Weather == \"Heat Index 95\" |\n                                  Weather == \"Clear to Partly Cloudy\" |\n                                  Weather == \"Clear Skies\" |\n                                  Weather == \"Clear skies\" |\n                                  Weather == \"Clear and warm\" |\n                                  Weather == \"Clear and sunny\" |\n                                  Weather == \"Clear and Sunny\" |\n                                  Weather == \"Clear and Cool\" |\n                                  Weather == \"Clear and cold\" |\n                                  Weather == \"Clear\", \"Sun\", \n                                ifelse(Weather == \"Snow\" |\n                                         Weather == \"Showers\" |\n                                         Weather == \"Scattered Showers\" |\n                                         Weather == \"Rainy\" |\n                                         Weather == \"Rain shower\" |\n                                         Weather == \"Rain likely, temps in low 40s.\" |\n                                         Weather == \"Rain Chance 40 %\" |\n                                         Weather == \"10% Chance of Rain\" |\n                                         Weather == \"30% Chance of Rain\" |\n                                         Weather == \"Cloudy, 50% change of rain\" |\n                                         Weather == \"Cloudy, chance of rain\" |\n                                         Weather == \"Cloudy, light snow accumulating 1-3\\\"\" |\n                                         Weather == \"Rain\" |\n                                         Weather == \"Rain Chance 40%\" |\n                                         Weather == \"Light Rain\" |\n                                         Weather == \"Heavy lake effect snow\" |\n                                         Weather == \"Cloudy, Rain\" |\n                                         Weather == \"Cloudy with periods of rain, thunder possible. Winds shifting to WNW, 10-20 mph.\", \"Rain\", \n                                       ifelse(Weather == \"Party Cloudy\" |\n                                                Weather == \"Partly Clouidy\" |\n                                                Weather == \"Partly Cloudy\" |\n                                                Weather == \"Partly cloudy\" |\n                                                Weather == \"Overcast\" |\n                                                Weather == \"Mostly Cloudy\" |\n                                                Weather == \"Mostly cloudy\" |\n                                                Weather == \"Hazy\"|\n                                                Weather == \"Coudy\" |\n                                                Weather == \"Cloudy, fog started developing in 2nd quarter\" |\n                                                Weather == \"Cloudy, chance of rain\" |\n                                                Weather == \"Cloudy and cool\" |\n                                                Weather == \"Cold\" |\n                                                Weather == \"Controlled Climate\" |\n                                                Weather == \"Cloudy and Cool\" |\n                                                Weather == \"Cloudy and cold\" |\n                                                Weather == \"Fair\" |\n                                                Weather == \"Mostly Coudy\" |\n                                                Weather == \"Cloudy\" |\n                                                Weather == \"cloudy\", \"Cloudy\", \n                                              ifelse(Weather == \"Partly clear\", \"Clear\", \n                                                     ifelse(Weather == \"N/A (Indoors)\" |\n                                                              Weather == \"N/A Indoor\" |\n                                                              Weather == \"Indoor\" |\n                                                              Weather == \"Indoors\", \"Indoor\", NA)))))),\n         Weather_group_alt = as.factor(ifelse(Weather == \"Sunny, Windy\" | \n                                      Weather == \"Sunny, highs to upper 80s\" |\n                                      Weather == \"Sunny Skies\" |\n                                      Weather == \"Sunny and cold\" |\n                                      Weather == \"Sunny and warm\" |\n                                      Weather == \"Sunny and clear\" |\n                                      Weather == \"Sunny\" |\n                                      Weather == \"Sun & clouds\" |\n                                      Weather == \"Mostly sunny\" |\n                                      Weather == \"Mostly Sunny\" |\n                                      Weather == \"Mostly Sunny Skies\" |\n                                      Weather == \"Partly sunny\" |\n                                      Weather == \"Partly Sunny\" |\n                                      Weather == \"Heat Index 95\" |\n                                      Weather == \"Clear to Partly Cloudy\" |\n                                      Weather == \"Clear Skies\" |\n                                      Weather == \"Clear skies\" |\n                                      Weather == \"Clear and warm\" |\n                                      Weather == \"Clear and sunny\" |\n                                      Weather == \"Clear and Sunny\" |\n                                      Weather == \"Clear and Cool\" |\n                                      Weather == \"Clear and cold\" |\n                                      Weather == \"Clear\" |\n                                      Weather == \"Party Cloudy\" |\n                                      Weather == \"Partly Clouidy\" |\n                                      Weather == \"Partly Cloudy\" |\n                                      Weather == \"Partly cloudy\" |\n                                      Weather == \"Overcast\" |\n                                      Weather == \"Mostly Cloudy\" |\n                                      Weather == \"Mostly cloudy\" |\n                                      Weather == \"Hazy\"|\n                                      Weather == \"Coudy\" |\n                                      Weather == \"Cloudy, fog started developing in 2nd quarter\" |\n                                      Weather == \"Cloudy, chance of rain\" |\n                                      Weather == \"Cloudy and cool\" |\n                                      Weather == \"Cloudy and cold\" |\n                                      Weather == \"Cloudy\" |\n                                      Weather == \"cloudy\" |\n                                      Weather == \"Controlled Climate\" |\n                                      Weather == \"Mostly Coudy\" |\n                                      Weather == \"Partly clear\" |\n                                      Weather == \"Cold\" |\n                                      Weather == \"Fair\" |\n                                      Weather == \"10% Chance of Rain\" |\n                                      Weather == \"Cloudy and Cool\" , \"No rain\", \n                                    ifelse(Weather == \"Snow\" |\n                                             Weather == \"Showers\" |\n                                             Weather == \"Scattered Showers\" |\n                                             Weather == \"Rainy\" |\n                                             Weather == \"Rain shower\" |\n                                             Weather == \"Rain likely, temps in low 40s.\" |\n                                             Weather == \"Rain Chance 40 %\" |\n                                             Weather == \"30% Chance of Rain\" |\n                                             Weather == \"Cloudy, 50% change of rain\" |\n                                             Weather == \"Cloudy, chance of rain\" |\n                                             Weather == \"Rain\" |\n                                             Weather == \"Rain Chance 40%\" |\n                                             Weather == \"Cloudy, light snow accumulating 1-3\\\"\" |\n                                             Weather == \"Light Rain\" |\n                                             Weather == \"Heavy lake effect snow\" |\n                                             Weather == \"Cloudy, Rain\" |\n                                             Weather == \"Cloudy with periods of rain, thunder possible. Winds shifting to WNW, 10-20 mph.\", \"Rain\", \n                                           ifelse(Weather == \"N/A (Indoors)\" |\n                                                    Weather == \"N/A Indoor\" |\n                                                    Weather == \"Indoor\" |\n                                                    Weather == \"Indoors\", \"Indoor\", NA))))) %>%\n  mutate(Weather_group_alt2 = as.factor(ifelse(Weather == \"Snow\" |\n                                       Weather == \"Showers\" |\n                                       Weather == \"Scattered Showers\" |\n                                       Weather == \"Rainy\" |\n                                       Weather == \"Rain shower\" |\n                                       Weather == \"Rain likely, temps in low 40s.\" |\n                                       Weather == \"Rain Chance 40 %\" |\n                                       Weather == \"30% Chance of Rain\" |\n                                       Weather == \"Cloudy, 50% change of rain\" |\n                                       Weather == \"Cloudy, chance of rain\" |\n                                       Weather == \"Rain\" |\n                                       Weather == \"Light Rain\" |\n                                       Weather == \"Heavy lake effect snow\" |\n                                       Weather == \"Cloudy, Rain\" |\n                                       Weather == \"Cloudy with periods of rain, thunder possible. Winds shifting to WNW, 10-20 mph.\", \"Rain\", \"No Rain\"))) %>%\n  mutate(PlayType_group = ifelse(PlayType == \"Pass\", \"Pass\",\n                                 ifelse(PlayType == \"Rush\", \"Rush\",\n                                        ifelse(PlayType == \"\" | PlayType == \"0\", NA, \"Kick\")))) %>%\n  mutate(Position_group = ifelse(Position == \"QB\", \"QB\",\n                                 ifelse(Position == \"C\" |\n                                          Position == \"G\" |\n                                          Position == \"T\" |\n                                          Position == \"DE\" |\n                                          Position == \"DT\" |\n                                          Position == \"OLB\" |\n                                          Position == \"ILB\" |\n                                          Position == \"MLB\" |\n                                          Position == \"LB\" |\n                                          Position == \"NT\", \"Contact\",\n                                        ifelse(Position == \"K\" |\n                                                 Position == \"P\", \"Special\",\n                                               ifelse(Position == \"Missing Data\", NA, \"Run\"))))) %>%\n  mutate(StadiumType_group = ifelse(StadiumType == \"\", NA,\n                                    ifelse(StadiumType == \"Cloudy\" |\n                                             StadiumType == \"Domed, Open\" |\n                                             StadiumType == \"Indoor, Open Roof\" |\n                                             StadiumType == \"Open\" |\n                                             StadiumType == \"Outddors\" |\n                                             StadiumType == \"Outdoors\" |\n                                             StadiumType == \"Retr. Roof - Open\" |\n                                             StadiumType == \"Bowl\" |\n                                             StadiumType == \"Dome\" |\n                                             StadiumType == \"Heinz Field\" |\n                                             StadiumType == \"Oudoor\" |\n                                             StadiumType == \"Outdoor\" |\n                                             StadiumType == \"Outdor\" |\n                                             StadiumType == \"Retr. Roof-Open\" |\n                                             StadiumType == \"Domed, open\" |\n                                             StadiumType == \"Ourdoor\" |\n                                             StadiumType == \"Outdoor Retr Roof-Open\" |\n                                             StadiumType == \"Outside\" |\n                                             StadiumType == \"Retractable Roof\", \"Open\", \"Closed\")))\n\n\n# Check the levels of the factor variables\n\nlevels(In_play_weatherclean$RosterPosition)\nlevels(In_play_weatherclean$StadiumType)    # Does not say a lot in my opinion, delete?\nlevels(In_play_weatherclean$FieldType)    # Same as Surface\nlevels(In_play_weatherclean$PlayType)\nlevels(In_play_weatherclean$Position)\nlevels(In_play_weatherclean$PositionGroup)    # Definition? Keep 1 of the 3 position variables?\n\nlevels(as.factor(In_play_weatherclean$StadiumType_group))\nlevels(In_play_weatherclean$Weather_group)\nlevels(as.factor(In_play_weatherclean$Temperature))\nsum(is.na(In_play_weatherclean$Temperature))\n\n\nIn_play_weatherclean <- In_play_weatherclean %>%\n  mutate(Temperature = ifelse(Temperature < 0, NA, Temperature)) %>%\n  mutate(BodyPart = ifelse(is.na(BodyPart), 0, BodyPart),\n         DM_M1 = ifelse(is.na(DM_M1), 0, DM_M1),\n         DM_M7 = ifelse(is.na(DM_M7), 0, DM_M7),\n         DM_M28 = ifelse(is.na(DM_M28), 0, DM_M28),\n         DM_M42 = ifelse(is.na(DM_M42), 0, DM_M42))\n\n\n\nIn_play_weatherclean2 <- In_play_weatherclean %>%\n  mutate(Weather1 = ifelse(is.na(Weather_group) & StadiumType == \"Closed Dome\", \"Indoor\",\n                                  ifelse(is.na(Weather_group) & StadiumType == \"Dome\", \"Indoor\",\n                                         ifelse(is.na(Weather_group) & StadiumType == \"Dome, closed\", \"Indoor\",\n                                                ifelse(is.na(Weather_group) & StadiumType == \"Domed, closed\", \"Indoor\",\n                                                       ifelse(is.na(Weather_group) & StadiumType == \"Indoor\", \"Indoor\",\n                                                              ifelse(is.na(Weather_group) & StadiumType == \"Indoors\", \"Indoor\", as.character(Weather_group))))))),\n         Weather2 = ifelse(is.na(Weather_group) & StadiumType == \"Closed Dome\", \"Indoor\",\n                           ifelse(is.na(Weather_group) & StadiumType == \"Dome\", \"Indoor\",\n                                  ifelse(is.na(Weather_group) & StadiumType == \"Dome, closed\", \"Indoor\",\n                                         ifelse(is.na(Weather_group) & StadiumType == \"Domed, closed\", \"Indoor\",\n                                                ifelse(is.na(Weather_group) & StadiumType == \"Indoor\", \"Indoor\",\n                                                       ifelse(is.na(Weather_group) & StadiumType == \"Indoors\", \"Indoor\", as.character(Weather_group_alt))))))),\n         Weather3 = ifelse(is.na(Weather_group) & StadiumType == \"Closed Dome\", \"Indoor\",\n                           ifelse(is.na(Weather_group) & StadiumType == \"Dome\", \"Indoor\",\n                                  ifelse(is.na(Weather_group) & StadiumType == \"Dome, closed\", \"Indoor\",\n                                         ifelse(is.na(Weather_group) & StadiumType == \"Domed, closed\", \"Indoor\",\n                                                ifelse(is.na(Weather_group) & StadiumType == \"Indoor\", \"Indoor\",\n                                                       ifelse(is.na(Weather_group) & StadiumType == \"Indoors\", \"No rain\", as.character(Weather_group_alt))))))),\n         Temperature1 = ifelse(is.na(Temperature) & Weather2 == \"Indoor\", 68, as.numeric(Temperature)),\n         Weather3 = ifelse(Weather3 == \"Indoor\", \"No rain\", as.character(Weather3))) %>%\n  dplyr::select(-c(Weather_group, Weather_group_alt, Weather_group_alt2))\n\nIn_play_weatherclean2 %>%\n  count(is.na(Temperature1))\n\n\nIn_play_weatherclean2 %>%\n  filter(Weather2 == \"Indoor\" & !is.na(Temperature)) %>%\n  summarise(m = mean(Temperature),\n            n = median(Temperature))\n\n\nIn_play_weatherclean2 <- In_play_weatherclean2 %>%\n  dplyr::select(-RosterPosition, -Weather, -PositionGroup, -Surface, -PlayType)\n\n\n\nIn_play_clean <- In_play_weatherclean2 %>%\n  mutate(Temperature_bin = ifelse(Temperature1 >= 68, \"Hot\", \n                                  ifelse(Temperature1 < 59, \"Cold\", \"Indifferent\")),\n         Temperature_alt = ifelse(Temperature1 >= 80, \"Hot\",\n                                  ifelse(Temperature1 < 59, \"Cold\",\n                                         \"Indifferent\")),\n         Injury = ifelse(BodyPart != \"0\", 1, 0)) %>%\n  dplyr::select(-c(Temperature))\n           \nIn_play_clean$PlayType_group <- as.factor(In_play_clean$PlayType_group)\nIn_play_clean$Position_group <- as.factor(In_play_clean$Position_group)\nIn_play_clean$StadiumType_group <- as.factor(In_play_clean$StadiumType_group)\n\n# Check the remaining NA's and calculate the percentage of missing values\n\nmd.pattern(In_play_clean)\n\nlevels(as.factor(In_play_clean$Position_group))\nnrow(In_play_clean)\nsum(complete.cases(In_play_clean))\nsum(!complete.cases(In_play_clean))\nsum(!complete.cases(In_play_clean))/sum(complete.cases(In_play_clean))\n\ncolSums(is.na(In_play_clean))/sum(complete.cases(In_play_clean)) *100\n\n\n\n# Transform the playerday variable\n\nIn_play_clean <- In_play_clean %>%\n  mutate(PlayerDay1 = ifelse(PlayerDay > 200, PlayerDay -273, as.numeric(PlayerDay) + 63),\n         Season = ifelse(PlayerDay > 200, 2, 1)) %>%\n  arrange(PlayerDay1)\n\nIn_play_playerday <- In_play_clean %>%\n  distinct(GameID, .keep_all = TRUE) %>%\n  arrange(PlayerKey, Season,PlayerDay1) %>%\n  group_by(PlayerKey, Season) %>%\n  mutate(Short_term = lag(PlayerDay1, default = NA),\n         Mid_term = lag(PlayerDay1, default = NA, n = 2L),\n         Long_term = lag(PlayerDay1, default = NA, n = 3L)) %>%\n  mutate(Short_term = PlayerDay1 - Short_term,\n         Mid_term = PlayerDay1 - Mid_term,\n         Long_term = PlayerDay1 - Long_term,\n         Short_term = ifelse(is.na(Short_term) | Short_term == \"-Inf\", 98, Short_term),\n         Mid_term = ifelse(is.na(Mid_term) | Mid_term == \"-Inf\", 105, Mid_term),\n         Long_term = ifelse(is.na(Long_term) | Long_term == \"-Inf\", 112, Long_term),\n         Short_bin = ifelse(Short_term <= 8, \"Short\",\n                          ifelse(Short_term > 8  & Short_term <= 16, \"Mid\", \"Long\")),\n         Mid_bin = ifelse(Mid_term <= 16,\"Short\",\n                          ifelse(Mid_term > 16 & Mid_term <= 24, \"Mid\", \"Long\")),\n         Long_bin = ifelse(Long_term <= 24, \"Short\",\n                           ifelse(Long_term > 24 & Long_term <= 48, \"Mid\", \"Long\"))) %>%\n  ungroup() %>%\n  as.data.frame() %>%\n  dplyr::select(PlayerKey:PlayKey, Season:Long_bin)\n\n\nIn_play_clean <- In_play_clean %>%\n  left_join(In_play_playerday, by = c(\"PlayerKey\", \"GameID\")) %>%\n  dplyr::select(-c(Season.y, PlayKey.y, PlayerDay))\n\n\n\n\n### Overview of cleaning\n\n## DOne:\n\n# 1: Feature engineering of Stadiumtype variable -> Indoor or outdoors\n# 2: Delete Surface variable and other non necessary variables\n# 3: Feature engineering and imputations of Weather variable\n# 4: Check the temperature variable and impute wrong values + imputations\n# 5: Feature engineering of playerposition, playday and playtype\n\n\n###------------------------------------------------------------------------------------###\n\n###--------------------------### Exploratory Analysis ###------------------------------###\n\n\n\n### Univeriate \n\n\nIn_play_clean %>%\n  filter(Position != \"Missing Data\") %>%\n  count(Position) %>%\n  ggplot(aes(x = reorder(Position,n), y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  geom_hline(aes(yintercept = mean(n), color = \"red\"), linetype = \"longdash\") +\n  coord_flip() +\n  theme_classic() +\n  ggtitle(\"Playerposition\") +\n  xlab(\"Position\") +\n  ylab(\"Count\") +\n  theme(legend.position = \"none\")\n\nIn_play_clean %>%\n  filter(!is.na(Position_group)) %>%\n  count(Position_group) %>%\n  ggplot(aes(x = reorder(Position_group,n), y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  coord_flip() +\n  theme_classic() +\n  ggtitle(\"Playerposition\") +\n  xlab(\"Position\") +\n  ylab(\"Count\") +\n  theme(legend.position = \"none\")\n\nIn_play_clean %>%\n  count(StadiumType_group) %>%\n  ggplot(aes(x = reorder(StadiumType_group,n), y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  coord_flip() +\n  theme_classic() +\n  ggtitle(\"Stadiumtype\") +\n  xlab(\"Position\") +\n  ylab(\"Count\") +\n  theme(legend.position = \"none\")\n\nIn_play_weatherclean %>%\n  count(Weather) %>%\n  ggplot(aes(x = reorder(Weather,n), y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  coord_flip() +\n  theme_classic() +\n  ggtitle(\"Weather\") +\n  xlab(\"Weather\") +\n  ylab(\"Count\") +\n  theme(legend.position = \"none\")\n  \n\n\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  ggplot(aes(x = Temperature)) +\n  geom_histogram(fill = \"darkblue\") +\n  theme_classic() +\n  ggtitle(\"Temperature during the games\") +\n  xlab(\"Temperature\") +\n  ylab(\"Count\")\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  count(BodyPart) %>%\n  ggplot(aes(x = BodyPart, y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  ggtitle(\"Which bodyparts got injured?\") +\n  xlab(\"Bodypart\") +\n  ylab(\"Count\")\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  count(FieldType) %>%\n  ggplot(aes(x = FieldType, y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  ggtitle(\"Surfaces\") +\n  xlab(\"Surface\") +\n  ylab(\"Count\")\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  pivot_longer(cols = DM_M1:DM_M42)  %>%\n  count(name, value) %>%\n  filter(value == 1) %>%\n  ggplot(aes(x = reorder(name, desc(n)), y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  ggtitle(\"Amount of days injured\") +\n  xlab(\"Amount of days injured\") +\n  ylab(\"Count\")\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  pivot_longer(cols = DM_M1:DM_M42)  %>%\n  count(name, value) %>%\n  filter(value == 1) %>%\n  mutate(days = ifelse(name == \"DM_M1\", 77-60,\n                       ifelse(name == \"DM_M7\", 60-31,\n                              ifelse(name == \"DM_M28\", 31-24,24))),\n         count = c(1,3,4,2)) %>%\n  ggplot(aes(x = reorder(name,count), y = days)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  ggtitle(\"Amount of days injured\") +\n  xlab(\"Amount of days injured\") +\n  ylab(\"Count\")\n  \n  \nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  count(Weather_group_alt) %>%\n  ggplot(aes(x = Weather_group_alt, y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  ggtitle(\"Weather\") +\n  xlab(\"Rain or no rain\") +\n  ylab(\"Count\")\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  count(PlayType_group) %>%\n  ggplot(aes(x = PlayType_group, y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  coord_flip() +\n  ggtitle(\"Playtype\") +\n  xlab(\"Playtype\") +\n  ylab(\"Count\")\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  count(Temperature_bin) %>%\n  ggplot(aes(x = Temperature_bin, y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  coord_flip() +\n  ggtitle(\"Temperature\") +\n  xlab(\"Temperature\") +\n  ylab(\"Count\")\n\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  count(Temperature_alt) %>%\n  ggplot(aes(x = Temperature_alt, y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  coord_flip() +\n  ggtitle(\"Temperature\") +\n  xlab(\"Temperature\") +\n  ylab(\"Count\")\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  ggplot(aes(x = Temperature1)) +\n  geom_histogram(fill = \"darkblue\") +\n  theme_classic() +\n  ggtitle(\"Playergame\")\n\nIn_play_clean %>%\n  filter(Injury == 0) %>%\n  ggplot(aes(x = Temperature1)) +\n  geom_histogram(fill = \"darkblue\") +\n  theme_classic() +\n  ggtitle(\"Playergame\")\n\nIn_play_clean %>%\n  ggplot(aes(x = as.factor(Injury), y = Temperature1)) +\n  geom_boxplot() +\n  theme_classic() +\n  ggtitle(\"Temperature during games\", subtitle = \"No Injury (0) vs Injury (1)\") +\n  xlab(\"No Injury (0) vs Injury (1)\") +\n  ylab(\"Temperature (°F)\")\n  \n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  count(Long_bin) %>%\n  ggplot(aes(x = Long_bin, y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  xlab(\"Long term matchload\") +\n  ylab(\"Amount\") +\n  ggtitle(\"Long term matchload of players\", subtitle = \"Injury group\")\n\n\nIn_play_clean %>%\n  filter(Injury == 0) %>%\n  count(Long_bin) %>%\n  ggplot(aes(x = Long_bin, y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  xlab(\"Long term matchload\") +\n  ylab(\"Amount\") +\n  ggtitle(\"Long term matchload of players\", subtitle = \"No injury group\")\n\n\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  ggplot(aes(x = FieldType, y = Temperature)) +\n  geom_boxplot() +\n  theme_classic()\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  ggplot(aes(x = Temperature)) +\n  geom_histogram() +\n  facet_wrap(~FieldType)\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  ggplot(aes(x = PlayerDay)) +\n  geom_histogram() +\n  facet_wrap(~FieldType)\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  ggplot(aes(x = PlayerGame)) +\n  geom_histogram() +\n  facet_wrap(~FieldType)\n\nIn_play_clean %>%\n  filter(Injury == 1) %>%\n  ggplot(aes(x = Temperature)) +\n  geom_histogram() +\n  facet_wrap(~StadiumType_group) +\n  theme_classic()\n\n### Conclusion: \n# 1: More games played on natural turf, relative more injuries on synthetic however\n# 2: More injuries of bodypart 1,4 on synthetic turf\n# 3: More injuries indoor\n# 4: Playtype possible important\n# 5: Temperature more spread outdoors and higher temperature value with injuries\n\n\n\n###--------------------------------------------------------------------------------------------\n\n### Check now the full amount of games played and injuries occured\n\nIn_play_clean %>%\n  distinct(GameID, .keep_all = TRUE) %>%\n  count(GameID, FieldType) %>%\n  count(FieldType) %>%\n  ggplot(aes(x = FieldType, y = n)) +\n  geom_bar(stat = \"identity\", fill = \"darkblue\") +\n  theme_classic() +\n  ggtitle(\"Fieldtype of NFL games\") +\n  ylab(\"Amount\")\n\n\nIn_play_clean %>%\n  ggplot() +\n  geom_mosaic(aes(x = product(FieldType), \n                  fill = FieldType)) +\n  coord_flip() +\n  facet_wrap(~Injury) +\n  theme_classic() +\n  theme(axis.text.x = element_blank(),\n        axis.ticks.x = element_blank()) +\n  xlab(\"Fieldtype\") +\n  ylab(\"No Injury (0) vs Injury (1)\") +\n  ggtitle(\"Proportions of injuries per Fieldtype\")\n  \n\n\n# More games are played on natural turf, although the most injuries occur on synthetic surface\n\nIn_play_clean %>%\n  count(Injury, GameID) %>%\n  filter(Injury > 1)\n\nIn_play_clean %>%\n  count(Injury, PlayKey.x) %>%\n  filter(Injury > 1)\n\n# No multiple injuries per game\n\n\n###----------------------------------------------------------------------------------###\n\n###----------------------------------- Analysis -------------------------------------###\n\n\n\n# Create a dataframe with different AIC scores for different models\n\nmodel_diff <- data.frame(Model = NA, AIC = NA)\n\n\n# No more than 1 injury per game, maybe this is the missing data of the injuries?\n\n\nfirst <- glm(data = In_play_clean, formula = Injury ~ FieldType, \n             family = binomial(link = 'logit'))\nfirst_sum <- summary(first) \n\n\nmodel_diff[1,1] <- \"FieldType\"\nmodel_diff[1,2] <- first_sum$aic\n\n\n\n# FieldType has indeed a significant effect on injuries, add confounder variables and interaction\n# to see whether this effect changes\n\nfield_wea <- glm(data = In_play_clean, formula = Injury ~ FieldType + Weather1, \n             family = binomial(link = 'logit'))\nsummary(field_wea) \n\nfield_wea2 <- glm(data = In_play_clean, formula = Injury ~ FieldType + Weather2, \n                 family = binomial(link = 'logit'))\nsummary(field_wea2) \n\nfield_wea3 <- glm(data = In_play_clean, formula = Injury ~ FieldType + Weather3, \n                  family = binomial(link = 'logit'))\nwea_sum <- summary(field_wea3) \n\nmodel_diff[2,1] <- \"Fieldtype and weather(Rain/No Rain)\"\nmodel_diff[2,2] <- wea_sum$aic\n\n# Rain/No Rain a possible confounder and marginally significant\n\nfield_temp <- glm(data = In_play_clean, formula = Injury ~ FieldType + Temperature_bin, \n             family = binomial(link = 'logit'))\nsummary(field_temp)\n\nfield_temp2 <- glm(data = In_play_clean, formula = Injury ~ FieldType + Temperature_alt, \n                  family = binomial(link = 'logit'))\nsummary(field_temp2) \n\nfield_temp3 <- glm(data = In_play_clean, formula = Injury ~ FieldType + Temperature1, \n                   family = binomial(link = 'logit'))\ntemp_sum <- summary(field_temp3) \nmodel_diff[3,1] <- \"Fieldtype and Temperature\"\nmodel_diff[3,2] <- temp_sum$aic\n\n\n# Temperature possible confounder\nIn_play_clean <- In_play_clean %>%\n  mutate(PlayType_group = factor(PlayType_group, levels = c(\"Pass\", \"Rush\", \"Kick\")))\nlevels(In_play_clean$PlayType_group)\nfield_play <- glm(data = In_play_clean, formula = Injury ~ FieldType + PlayType_group, \n             family = binomial(link = 'logit'))\nsummary(field_play) \n\nlevels(In_play_clean$Position_group)\nfield_pos <- glm(data = In_play_clean, formula = Injury ~ FieldType + Position_group, \n                 family = binomial(link = 'logit'))\nsummary(field_pos)\n\nfield_stadium <- glm(data = In_play_clean, formula = Injury ~ FieldType + StadiumType_group, \n                 family = binomial(link = 'logit'))\nsummary(field_stadium)\n\n\nfield_bodypart <- glm(data = In_play_clean, formula = Injury ~ FieldType + as.factor(BodyPart), \n                     family = binomial(link = 'logit'))\nsummary(field_bodypart)\n\nfield_long <- glm(data = In_play_clean, formula = Injury ~ FieldType + as.factor(Long_bin),\n              family = binomial(link = 'logit'))\nlong_sum <- summary(field_long)\n\nmodel_diff[4,1] <- \"Fieldtype and longterm matchload\"\nmodel_diff[4,2] <- long_sum$aic \n\nfield_mid <- glm(data = In_play_clean, formula = Injury ~ FieldType + as.factor(Mid_bin),\n                 family = binomial(link = 'logit'))\nsummary(field_mid)\n\nfield_short <- glm(data = In_play_clean, formula = Injury ~ FieldType + as.factor(Short_bin),\n                 family = binomial(link = 'logit'))\nsummary(field_short)\n\n\n### Temperature and playtype significant? However, no injuries in kick level of playtype, discard?\n### One of the terms and Weather3 also significant\n\nfield_temp_wea <- glm(data = In_play_clean, \n                           formula = Injury ~ FieldType + Temperature1 + Weather3, \n                           family = binomial(link = 'logit'))\ntemp_wea_sum <- summary(field_temp_wea) \nmodel_diff[5,1] <- \"Fieldtype, Temperature and weather(Rain/No rain)\"\nmodel_diff[5,2] <- temp_wea_sum$aic \n\nfield_temp_pltype <- glm(data = In_play_clean, \n                      formula = Injury ~ FieldType + Temperature1 + PlayType_group, \n                      family = binomial(link = 'logit'))\nsummary(field_temp_pltype) \n\nfield_temp_short <- glm(data = In_play_clean, \n                      formula = Injury ~ FieldType + Temperature1 + Short_bin, \n                      family = binomial(link = 'logit'))\nsummary(field_temp_short) \n\nfield_temp_mid <- glm(data = In_play_clean, \n                      formula = Injury ~ FieldType + Temperature1 + Mid_bin, \n                      family = binomial(link = 'logit'))\nsummary(field_temp_mid) \n\nfield_temp_long <- glm(data = In_play_clean, \n                      formula = Injury ~ FieldType + Temperature1 + Long_bin, \n                      family = binomial(link = 'logit'))\ntemp_long_sum <- summary(field_temp_long) \n\nmodel_diff[6,1] <- \"Fieldtype, temperature and long term matchload\"\nmodel_diff[6,2] <- temp_long_sum$aic \n\n\n\n### \n\nfield_temp_long_wea <- glm(data = In_play_clean, \n                       formula = Injury ~ FieldType + Temperature1 + Long_bin + Weather3, \n                       family = binomial(link = 'logit'))\ntemp_long_wea_sum <- summary(field_temp_long_wea) \n\nmodel_diff[7,1] <- \"Fieldtype, temperature, weather(Rain/No rain) and long term matchload\"\nmodel_diff[7,2] <- temp_long_wea_sum$aic\n\n\nfield_temp_long_wea_inttemp <- glm(data = In_play_clean, \n                           formula = Injury ~ FieldType + Temperature1 + Long_bin + Weather3 +\n                             FieldType:Temperature1, \n                           family = binomial(link = 'logit'))\ntemp_long_wea_inttemp_sum <- summary(field_temp_long_wea_inttemp) \n\nmodel_diff[8,1] <- \"Fieldtype, temperature, weather, long term matchload and interaction temperature\"\nmodel_diff[8,2] <- temp_long_wea_inttemp_sum$aic\n\nfield_temp_long_wea_intlong <- glm(data = In_play_clean, \n                                   formula = Injury ~ FieldType + Temperature1 + Long_bin + Weather3 +\n                                     FieldType:Long_bin, \n                                   family = binomial(link = 'logit'))\ntemp_long_wea_intlong_sum <- summary(field_temp_long_wea_intlong) \n\nmodel_diff[9,1] <- \"Fieldtype, temperature, weather, long term matchload and interaction long term matchload\"\nmodel_diff[9,2] <- temp_long_wea_intlong_sum$aic\n\nfield_temp_long_wea_intwea <- glm(data = In_play_clean, \n                                   formula = Injury ~ FieldType + Temperature1 + Long_bin + Weather3 +\n                                     FieldType:Weather3, \n                                   family = binomial(link = 'logit'))\ntemp_long_wea_intwea_sum <- summary(field_temp_long_wea_intwea) \n\nmodel_diff[10,1] <- \"Fieldtype, temperature, weather, long term matchload and interaction weather\"\nmodel_diff[10,2] <- temp_long_wea_intwea_sum$aic\n\n\nIn_play_clean_alt <- In_play_clean %>%\n  filter(DM_M28 == 1 |\n         DM_M42 == 1 |\n           BodyPart == 0)\n\nfield_temp_long_wea_alt <- glm(data = In_play_clean_alt, \n                           formula = Injury ~ FieldType + Temperature1 + \n                             Long_bin + Weather3 + PlayType_group, \n                           family = binomial(link = \"logit\"))\ntemp_long_wea_sum_alt <- summary(field_temp_long_wea_alt) \n\n\n### Automatic variable selection by forward or backward selection\nIn_play_clean2 <- In_play_clean %>%\n  dplyr::select(FieldType, Position_group, Weather3, Temperature1, Injury, \n         Long_bin)\n\n\nfull_model <- glm(data = In_play_clean2[complete.cases(In_play_clean2),], \n                  formula = Injury~(.)^2, \n                  family = binomial(link = 'logit'))\n\nstep.model <- stepAIC(full_model, direction = \"both\", \n                      trace = FALSE)\nsummary(step.model)\n\n\n\n### Make predictions\npred <- data.frame(Turf = NA, Temperature = NA, Weather = NA, long = NA, prediction = NA)\npred[1,5] <- predict.glm(field_temp_long_wea, newdata = data.frame(FieldType = \"Synthetic\",\n                                                         Temperature1 = 50,\n                                                          Weather3 = \"Rain\",\n                                                         Long_bin = \"Long\"),\n            type = \"response\")\n\npred[2,5] <- predict.glm(field_temp_long_wea, newdata = data.frame(FieldType = \"Natural\",\n                                                         Temperature1 = 50,\n                                                         Weather3 = \"Rain\",\n                                                         Long_bin = \"Long\"),\n            type = \"response\")\n\npred[3,5] <- predict.glm(field_temp_long_wea, newdata = data.frame(FieldType = \"Synthetic\",\n                                                         Temperature1 = 80,\n                                                         Weather3 = \"Rain\",\n                                                         Long_bin = \"Long\"),\n            type = \"response\")\n\npred[4,5] <- predict.glm(field_temp_long_wea, newdata = data.frame(FieldType = \"Natural\",\n                                                         Temperature1 = 80,\n                                                         Weather3 = \"Rain\",\n                                                         Long_bin = \"Long\"),\n            type = \"response\")\n\n\n\npred[5,5] <- predict.glm(field_temp_long_wea, newdata = data.frame(FieldType = \"Synthetic\",\n                                                                   Temperature1 = 50,\n                                                                   Weather3 = \"No rain\",\n                                                                   Long_bin = \"Long\"),\n                         type = \"response\")\n\npred[6,5] <- predict.glm(field_temp_long_wea, newdata = data.frame(FieldType = \"Natural\",\n                                                                   Temperature1 = 50,\n                                                                   Weather3 = \"No rain\",\n                                                                   Long_bin = \"Long\"),\n                         type = \"response\")\n\npred[7,5] <- predict.glm(field_temp_long_wea, newdata = data.frame(FieldType = \"Synthetic\",\n                                                                   Temperature1 = 80,\n                                                                   Weather3 = \"No rain\",\n                                                                   Long_bin = \"Long\"),\n                         type = \"response\")\n\npred[8,5] <- predict.glm(field_temp_long_wea, newdata = data.frame(FieldType = \"Natural\",\n                                                                   Temperature1 = 80,\n                                                                   Weather3 = \"No rain\",\n                                                                   Long_bin = \"Long\"),\n                         type = \"response\")\n\n\n\npred[c(1,3,5,7),1] <- \"Synthetic\"\npred[c(2,4,6,8),1] <- \"Natural\"\npred[c(1,2,5,6),2] <- 50\npred[c(3,4,7,8),2] <- 80\npred[c(1,2,3,4),3] <- \"Rain\"\npred[c(5,6,7,8),3] <- \"No Rain\"\n\n\npred %>%\n  mutate(prediction = prediction*100) %>%\nggplot(aes(x = Temperature, y= prediction, color = Turf)) +\n  geom_point() + \n  geom_line() +\n  theme_classic() +\n  facet_wrap(~Weather) +\n  ggtitle(\"Percentage chance to sustain an injury in a play\", \n          subtitle = \"Comparison of turf type and temperature for \\nplayers with a low match load\") +\n  ylab(\"% chance to sustain an injury\")\n\n\n\n\n","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}