{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# **<<< 1. DATA HANDLING >>>**\n",
        "\n",
        "# installing packages"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754394082373
        },
        "jupyter": {
          "outputs_hidden": false
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "install.packages(\n",
        "    c(  \n",
        "        # data handling and plotting\n",
        "        \"tidyverse\",\n",
        "        \"ragg\",\n",
        "        \"writexl\",\n",
        "        \"knitr\",\n",
        "        \"janitor\",\n",
        "        \"scales\",\n",
        "        \"ggsci\",\n",
        "        \"patchwork\",\n",
        "        \"UpSetR\",\n",
        "        \"ComplexUpset\",\n",
        "        # time series analysis\n",
        "        #\"lme4\",\n",
        "        #\"performance\",\n",
        "        #\"mgcv\",\n",
        "        #\"MuMIn\",\n",
        "        #\"broom.mixed\",\n",
        "        #\"gt\",\n",
        "        #\"fable\",\n",
        "        # association matrix analysis\n",
        "        \"FactoMineR\",\n",
        "        \"factoextra\"\n",
        "        ),\n",
        "        repos=\"http://nexus.tde.imperial.nhs.uk:8081/repository/cran/\",\n",
        "        lib=\"/home/azureuser/R\"\n",
        "        )\n",
        "\n",
        "# setting default library path\n",
        ".libPaths(\"/home/azureuser/R\")\n",
        "\n",
        "# data handling and plotting\n",
        "library(tidyverse)\n",
        "library(ragg)\n",
        "library(writexl)\n",
        "library(knitr)\n",
        "library(janitor)\n",
        "library(scales)\n",
        "library(ggsci)\n",
        "library(patchwork)\n",
        "library(UpSetR)\n",
        "library(ComplexUpset)\n",
        "\n",
        "# time series analysis\n",
        "#library(lme4)\n",
        "#library(performance)\n",
        "#library(mgcv)\n",
        "#library(MuMIn)\n",
        "#library(broom.mixed)\n",
        "#library(gt)\n",
        "#library(fable)\n",
        "\n",
        "# association matrix analysis\n",
        "library(FactoMineR)\n",
        "library(factoextra)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## lean load"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754564872039
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# removing everything other than base R\n",
        "#pks <- setdiff(installed.packages()[, \"Package\"], rownames(installed.packages(priority = \"base\")))\n",
        "\n",
        "#remove.packages(pks)\n",
        "\n",
        "# installing only tidyverse\n",
        "install.packages(\n",
        "    c(\"tidyverse\",\n",
        "       \"ggsci\",\n",
        "       \"knitr\"\n",
        "       #\"ComplexUpset\",\n",
        "       #\"UpSetR\"\n",
        "       ),\n",
        "repos=\"http://nexus.tde.imperial.nhs.uk:8081/repository/cran/\",\n",
        "        lib=\"/home/azureuser/R\"\n",
        "        )\n",
        "\n",
        "library(tidyverse)\n",
        "library(ggsci)\n",
        "library(knitr)\n",
        "#library(ComplexUpset)\n",
        "#library(UpSetR)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## checking packages"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754394277886
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# list all packages\n",
        "#installed.packages()[,\"Package\"]\n",
        "\n",
        "# find specific packages\n",
        "\"package::FactoMineR\" %in% search()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## adding late-install packages\n",
        "\n",
        "### make sure to include above for next time"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754394487810
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "install.packages(\n",
        "        #\"ComplexUpset\",\n",
        "        #\"FactoMineR\",\n",
        "        \"factoextra\",\n",
        "        repos=\"http://nexus.tde.imperial.nhs.uk:8081/repository/cran/\",\n",
        "        dependencies=TRUE,\n",
        "        lib=\"/home/azureuser/R\"\n",
        "        )\n",
        "\n",
        "# setting default library path\n",
        ".libPaths(\"/home/azureuser/R\") \n",
        "\n",
        "#library(ComplexUpset)\n",
        "#library(FactoMineR)\n",
        "library(factoextra)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## checking package versions"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1749460916387
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "pkgs <- installed.packages()[, c(\"Package\", \"Version\")]\n",
        "\n",
        "pkgs <- as.data.frame(pkgs, stringsAsFactors = F)\n",
        "\n",
        "pkgs$Citation <- vapply(\n",
        "    pkgs$Package,\n",
        "    function(pkg) {\n",
        "        tryCatch(\n",
        "            {\n",
        "            cit <- citation(pkg)\n",
        "            paste(format(cit, style = \"text\")[1], collapse = \" \")\n",
        "            },\n",
        "            error = function(e) \"No Citation Found\"\n",
        "        )\n",
        "\n",
        "    },\n",
        "    character(1)\n",
        ")\n",
        "\n",
        "pkgs"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## individual packages"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1749461568058
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "packageVersion(\"stats\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# uploading data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1749218021905
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# microbiology data\n",
        "micro <- read.csv(\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/microbiology_pull_final_08042025.csv\")\n",
        "# demographics data\n",
        "demographics <- read.csv(\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/demographics_pull_final_10032025.csv\")\n",
        "# episodes data\n",
        "episodes <-  read.csv(\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/episodes_pull_final_10032025.csv\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## data are slow to upload so creating checkpoint data to carry forward\n",
        "\n",
        "### three different \"buttons\" easiest to use when fixing errors that may occur below"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1749218052313
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "micro_cf <- micro"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1749218053817
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "demographics_cf <- demographics"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1749218055226
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "episodes_cf <- episodes"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## reclassifying date columns\n",
        "\n",
        "### microbiology data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1749218617585
        },
        "jupyter": {
          "outputs_hidden": false
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "micro_cf<-micro_cf |>\n",
        "  mutate(SAMPLE_COLLECTED_DT = lubridate::as_date(ymd_hms(SAMPLE_COLLECTED_DT)))\n",
        "class(micro_cf$SAMPLE_COLLECTED_DT)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "### episodes data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706331344
        },
        "jupyter": {
          "outputs_hidden": false
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "episodes_cf<-episodes_cf |>\n",
        "  mutate(across(c(ADMISSION_DATE, EPISODE_START_DATE, EPISODE_END_DATE, DISCHARGE_DATE), ymd))\n",
        "class(episodes_cf$ADMISSION_DATE)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# cleaning demographics data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706334575
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "print(\"before:\")\n",
        "levels(as.factor(demographics_cf$ETHNICITY_DESC))\n",
        "\n",
        "demographics_cf <-\n",
        "demographics_cf |>\n",
        "  mutate(ETHNICITY_DESC = fct_collapse(ETHNICITY_DESC,\n",
        "    Asian = c(\"asian or asian british - bangladeshi\",\n",
        "              \"asian or asian british - indian\",\n",
        "              \"asian or asian british - pakistani\",\n",
        "              \"asian - any other asian background\",\n",
        "              \"chinese\",\n",
        "              \"other - chinese\"),\n",
        "    White = c(\"white - british\",\n",
        "              \"white - irish\",\n",
        "              \"white - any other white background\"),\n",
        "    Black = c(\"black or black british - african\",\n",
        "              \"african (except somali)\",\n",
        "              \"black or black british - caribbean\",\n",
        "              \"black - any other black background\"),\n",
        "    Mixed = c(\"mixed - white and asian\",\n",
        "              \"white and asian\",\n",
        "              \"mixed - white and black african\",\n",
        "              \"mixed - white and black caribbean\",\n",
        "              \"mixed - any other mixed background\"),\n",
        "    Other = c(\"other - any other ethnic group\",\n",
        "              \"any other ethnic group\",\n",
        "              \"not known\",\n",
        "              \"not stated\",\n",
        "              \"british\",\n",
        "              \"other - not stated\",\n",
        "              \"other - not known\")\n",
        "  ))\n",
        "\n",
        "print(\"after:\")\n",
        "levels(as.factor(demographics_cf$ETHNICITY_DESC))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# cleaning microbiology data\n",
        "\n",
        "## defining all susceptibility testing data **and** blood cultures only susceptibility testing data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706350262
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# all microbiology susceptibility testing data\n",
        "micro_cf_ALL <-\n",
        "micro_cf |>\n",
        "    # removing colums where sensitivity is NA or does not contain \":\"\n",
        "    filter(!is.na(SENSITIVITY) & str_detect(SENSITIVITY, \":\")) |>\n",
        "    # filtering for susceptiblity testing data\n",
        "    filter(str_detect(ORDER_NAME, \"susceptibility\"))\n",
        "\n",
        "# creating intermediate data frame for left_join\n",
        "df <-\n",
        "micro_cf |>\n",
        "    # filtering for blood cultures only\n",
        "    filter(str_detect(ORDER_NAME, \"blood\"))\n",
        "\n",
        "# blood cultures only susceptibility testing data\n",
        "micro_cf_BLOOD <-\n",
        "micro_cf_ALL |>\n",
        "    left_join(df |>\n",
        "                # selecting only columns of interest\n",
        "                select(SUBJECT,\n",
        "                       SAMPLE_COLLECTED_DT,\n",
        "                       CULTURE_TYPE=ORDER_NAME),\n",
        "                by = c(\"SUBJECT\",\n",
        "                       \"SAMPLE_COLLECTED_DT\"),\n",
        "                relationship = \"many-to-many\") |>\n",
        "    # moving new column before bugs column\n",
        "    relocate(CULTURE_TYPE,.before = \"ORGANISM_BUG\") |>\n",
        "    filter(!is.na(CULTURE_TYPE)) |>\n",
        "    distinct()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## checking data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706357178
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "print(\"All microbiology susceptibility testing data:\")\n",
        "head(micro_cf_ALL)\n",
        "print(\"Number of records in all microbiology susceptibility testing data:\")\n",
        "length(micro_cf_ALL$SUBJECT)\n",
        "print(\"Number of distinct patients in all microbiology susceptibility testing  data:\")\n",
        "n_distinct(micro_cf_ALL$SUBJECT)\n",
        "\n",
        "print(\"Blood cultures only susceptibility testing data:\")\n",
        "head(micro_cf_BLOOD)\n",
        "print(\"Number of records in blood cultures only susceptibility testing data:\")\n",
        "length(micro_cf_BLOOD$SUBJECT)\n",
        "print(\"Number of distinct patients in blood cultures only susceptibility testing data:\")\n",
        "n_distinct(micro_cf_BLOOD$SUBJECT)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## defining bugs and basic column fixes\n",
        "\n",
        "### all microbiology susceptibility testing data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706439710
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "micro_cf_ALL <-\n",
        "micro_cf_ALL |>\n",
        "    # removing colums where sensitivity is NA or does not contain \":\"\n",
        "    filter(!is.na(SENSITIVITY) & str_detect(SENSITIVITY, \":\")) |>\n",
        "    # focussing only on susceptiblity testing data\n",
        "    filter(str_detect(ORDER_NAME, \"susceptibility\")) |>\n",
        "    # copying original bugs column\n",
        "    mutate(OLD_BUGS=ORGANISM_BUG) |>\n",
        "    # removing special symbols in bugs column and creating new column\n",
        "    mutate(ORGANISM_OR_BUG = str_replace_all(OLD_BUGS, \"[^[:alnum:] ]\", \"\")\n",
        "    ) |>\n",
        "    # identifying bugs\n",
        "    mutate(\n",
        "    ORGANISM_OR_BUG = case_when(\n",
        "      # Klebsiella pneumoniae\n",
        "      str_detect(ORGANISM_OR_BUG, \"klebsiella pneumoniae\") ~ \"Klebsiella pneumoniae\",\n",
        "      # Klebsiella species\n",
        "      str_detect(ORGANISM_OR_BUG, \"klebsiella\") & ORGANISM_OR_BUG != \"Klebsiella pneumoniae\" ~ \"Klebsiella spp.\",\n",
        "      # E. coli\n",
        "      str_detect(ORGANISM_OR_BUG, regex(\"escherichia coli|e.coli\", ignore_case = TRUE)) ~ \"Escherichia coli\",\n",
        "      # Citrobacter species\n",
        "      str_detect(ORGANISM_OR_BUG, \"citrobacter\") ~ \"Citrobacter spp.\",\n",
        "      # Enterobacter species\n",
        "      str_detect(ORGANISM_OR_BUG, \"enterobacter\") ~ \"Enterobacter spp.\",\n",
        "      # Proteus species\n",
        "      str_detect(ORGANISM_OR_BUG, \"proteus\") ~ \"Proteus spp.\",\n",
        "      # Serratia species\n",
        "      str_detect(ORGANISM_OR_BUG, \"serratia\") ~ \"Serratia spp.\",\n",
        "      # other species (e.g., Gram positives)\n",
        "      TRUE ~ \"Other, including Gram +ves\"\n",
        "    )) |>\n",
        "    # relevelling factor\n",
        "    mutate(\n",
        "    ORGANISM_OR_BUG=factor(ORGANISM_OR_BUG,\n",
        "      levels = c(\"Escherichia coli\",\n",
        "                  \"Klebsiella pneumoniae\",\n",
        "                  \"Citrobacter spp.\",\n",
        "                  \"Enterobacter spp.\",\n",
        "                  \"Hafnia alvei\",\n",
        "                  \"Klebsiella spp.\",\n",
        "                  \"Morganella morganii\",\n",
        "                  \"Proteus spp.\",\n",
        "                  \"Serratia spp.\",\n",
        "                  \"Other, including Gram +ves\"\n",
        "    ))) |>\n",
        "    # splitting sensitivity column into 2 columns\n",
        "    separate(SENSITIVITY, into = c(\"DRUG\", \"SUSCEPTIBILITY\"), sep = \" : \") |>\n",
        "    # capitalising drugs and susceptibility values\n",
        "    mutate(DRUG = str_to_title(DRUG),\n",
        "           SUSCEPTIBILITY = str_to_title(SUSCEPTIBILITY)) |>\n",
        "    select(SUBJECT,\n",
        "           SAMPLE_COLLECTED_DT,\n",
        "           OLD_BUGS,\n",
        "           ORGANISM_OR_BUG,\n",
        "           DRUG,\n",
        "           SUSCEPTIBILITY) |>\n",
        "    # filtering where no valid drug sensitivity\n",
        "    filter(!is.na(SUSCEPTIBILITY))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "### blood cultures only susceptibility testing data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706460116
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "micro_cf_BLOOD <-\n",
        "micro_cf_BLOOD |>\n",
        "    # removing colums where sensitivity is NA or does not contain \":\"\n",
        "    filter(!is.na(SENSITIVITY) & str_detect(SENSITIVITY, \":\")) |>\n",
        "    # focussing only on susceptiblity testing data\n",
        "    filter(str_detect(ORDER_NAME, \"susceptibility\")) |>\n",
        "    # copying original bugs column\n",
        "    mutate(OLD_BUGS=ORGANISM_BUG) |>\n",
        "    # removing special symbols in bugs column and creating new column\n",
        "    mutate(ORGANISM_OR_BUG = str_replace_all(OLD_BUGS, \"[^[:alnum:] ]\", \"\")\n",
        "    ) |>\n",
        "    # identifying bugs\n",
        "    mutate(\n",
        "    ORGANISM_OR_BUG = case_when(\n",
        "      # Klebsiella pneumoniae\n",
        "      str_detect(ORGANISM_OR_BUG, \"klebsiella pneumoniae\") ~ \"Klebsiella pneumoniae\",\n",
        "      # Klebsiella species\n",
        "      str_detect(ORGANISM_OR_BUG, \"klebsiella\") & ORGANISM_OR_BUG != \"Klebsiella pneumoniae\" ~ \"Klebsiella spp.\",\n",
        "      # E. coli\n",
        "      str_detect(ORGANISM_OR_BUG, regex(\"escherichia coli|e.coli\", ignore_case = TRUE)) ~ \"Escherichia coli\",\n",
        "      # Citrobacter species\n",
        "      str_detect(ORGANISM_OR_BUG, \"citrobacter\") ~ \"Citrobacter spp.\",\n",
        "      # Enterobacter species\n",
        "      str_detect(ORGANISM_OR_BUG, \"enterobacter\") ~ \"Enterobacter spp.\",\n",
        "      # Proteus species\n",
        "      str_detect(ORGANISM_OR_BUG, \"proteus\") ~ \"Proteus spp.\",\n",
        "      # Serratia species\n",
        "      str_detect(ORGANISM_OR_BUG, \"serratia\") ~ \"Serratia spp.\",\n",
        "      # other species (e.g., Gram positives)\n",
        "      TRUE ~ \"Other, including Gram +ves\"\n",
        "    )) |>\n",
        "    # relevelling factor\n",
        "    mutate(\n",
        "    ORGANISM_OR_BUG=factor(ORGANISM_OR_BUG,\n",
        "      levels = c(\"Escherichia coli\",\n",
        "                  \"Klebsiella pneumoniae\",\n",
        "                  \"Citrobacter spp.\",\n",
        "                  \"Enterobacter spp.\",\n",
        "                  \"Hafnia alvei\",\n",
        "                  \"Klebsiella spp.\",\n",
        "                  \"Morganella morganii\",\n",
        "                  \"Proteus spp.\",\n",
        "                  \"Serratia spp.\",\n",
        "                  \"Other, including Gram +ves\"\n",
        "    ))) |>\n",
        "    # splitting sensitivity column into 2 columns\n",
        "    separate(SENSITIVITY, into = c(\"DRUG\", \"SUSCEPTIBILITY\"), sep = \" : \") |>\n",
        "    # capitalising drugs and susceptibility values\n",
        "    mutate(DRUG = str_to_title(DRUG),\n",
        "           SUSCEPTIBILITY = str_to_title(SUSCEPTIBILITY)) |>\n",
        "    select(SUBJECT,\n",
        "           SAMPLE_COLLECTED_DT,\n",
        "           CULTURE_TYPE,\n",
        "           OLD_BUGS,\n",
        "           ORGANISM_OR_BUG,\n",
        "           DRUG,\n",
        "           SUSCEPTIBILITY) |>\n",
        "    # filtering where no valid drug sensitivity\n",
        "    filter(!is.na(SUSCEPTIBILITY))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## dealing with breakpoint values\n",
        "\n",
        "### which drugs have breakpoint values that need to be decoded?"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706734793
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "drugs_to_decode <-\n",
        "#micro_cf_ALL |>\n",
        "micro_cf_BLOOD |>\n",
        "# filtering out actual written values for susceptibility\n",
        "filter(str_count(SUSCEPTIBILITY, \"[A-Za-z]\") < 2) |>\n",
        "    select(DRUG) |>\n",
        "    distinct() |>\n",
        "    arrange(DRUG)\n",
        "\n",
        "kable(drugs_to_decode)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "### loading breakpoints data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706483925
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# microbiology data\n",
        "mic_breakpoints <- read.csv(\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/AB_guidelines.csv\")\n",
        "head(mic_breakpoints)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## tidying susceptibility column\n",
        "\n",
        "### all microbiology susceptibility testing data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706494705
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "print(\"before:\")\n",
        "levels(as.factor(micro_cf_ALL$SUSCEPTIBILITY))\n",
        "\n",
        "micro_cf_ALL <-\n",
        "micro_cf_ALL |> \n",
        "    mutate(SUSCEPTIBILITY = case_when(\n",
        "        # values to change\n",
        "        SUSCEPTIBILITY == \"Highly Resistant\" ~ \"Resistant\",\n",
        "        SUSCEPTIBILITY %in% c(\"Susceptible With Optimised Dosing, Refer To Antimicrobial Policy\",\"Sensitive\") ~ \"Susceptible\",\n",
        "        SUSCEPTIBILITY == \"Not Determined.\" ~ \"Not Determined\",\n",
        "        TRUE ~ SUSCEPTIBILITY\n",
        "    )) |>\n",
        "    # !!! addressing MIC breakpoint values !!!\n",
        "    # remove special symbols, \"=\", \">\", and \"<\"\n",
        "    mutate(SUSCEPTIBILITY = str_remove_all(SUSCEPTIBILITY,\"[=><]\")) |>\n",
        "    mutate(DRUG = toupper(DRUG)) |>\n",
        "    # left joining with breakpoints data\n",
        "    left_join(mic_breakpoints |>\n",
        "                # selecting columns of interest\n",
        "                select(DRUG,S,R),\n",
        "            by = \"DRUG\"\n",
        "            ) |>\n",
        "    # decoding MIC values\n",
        "    mutate(DECODED = case_when(\n",
        "        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) >= R ~ \"Resistant\",\n",
        "        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) <= S ~ \"Susceptible\",\n",
        "        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) > S & as.numeric(SUSCEPTIBILITY) < R ~ \"Intermediate\",\n",
        "    TRUE ~ as.character(SUSCEPTIBILITY)\n",
        "    )) |>\n",
        "    # checking decoding logic\n",
        "    #filter(str_detect(SUSCEPTIBILITY,\"\\\\d\")) |>\n",
        "    # filtering \"bad\" values, not captured by scalable logic\n",
        "    filter(DECODED %in% c(\"Resistant\",\"Intermediate\",\"Susceptible\",\"Not Determined\"))\n",
        "\n",
        "print(\"after:\")\n",
        "levels(as.factor(micro_cf_ALL$DECODED))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "### blood cultures only susceptibility testing data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706501392
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "print(\"before:\")\n",
        "levels(as.factor(micro_cf_BLOOD$SUSCEPTIBILITY))\n",
        "\n",
        "micro_cf_BLOOD <-\n",
        "micro_cf_BLOOD |> \n",
        "    mutate(SUSCEPTIBILITY = case_when(\n",
        "        # values to change\n",
        "        SUSCEPTIBILITY == \"Highly Resistant\" ~ \"Resistant\",\n",
        "        SUSCEPTIBILITY %in% c(\"Susceptible With Optimised Dosing, Refer To Antimicrobial Policy\",\"Sensitive\") ~ \"Susceptible\",\n",
        "        SUSCEPTIBILITY == \"Not Determined.\" ~ \"Not Determined\",\n",
        "        TRUE ~ SUSCEPTIBILITY\n",
        "    )) |>\n",
        "    # !!! addressing MIC breakpoint values !!!\n",
        "    # remove special symbols, \"=\", \">\", and \"<\"\n",
        "    mutate(SUSCEPTIBILITY = str_remove_all(SUSCEPTIBILITY,\"[=><]\")) |>\n",
        "    mutate(DRUG = toupper(DRUG)) |>\n",
        "    # left joining with breakpoints data\n",
        "    left_join(mic_breakpoints |>\n",
        "                # selecting columns of interest\n",
        "                select(DRUG,S,R),\n",
        "            by = \"DRUG\"\n",
        "            ) |>\n",
        "    # decoding MIC values\n",
        "    mutate(DECODED = case_when(\n",
        "        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) >= R ~ \"Resistant\",\n",
        "        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) <= S ~ \"Susceptible\",\n",
        "        !is.na(SUSCEPTIBILITY) & as.numeric(SUSCEPTIBILITY) > S & as.numeric(SUSCEPTIBILITY) < R ~ \"Intermediate\",\n",
        "    TRUE ~ as.character(SUSCEPTIBILITY)\n",
        "    )) |>\n",
        "    # checking decoding logic\n",
        "    #filter(str_detect(SUSCEPTIBILITY,\"\\\\d\")) |>\n",
        "    # filtering \"bad\" values, not captured by scalable logic\n",
        "    filter(DECODED %in% c(\"Resistant\",\"Intermediate\",\"Susceptible\",\"Not Determined\"))\n",
        "\n",
        "print(\"after:\")\n",
        "levels(as.factor(micro_cf_BLOOD$DECODED))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## defining drug classes"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "### all microbiology susceptibility testing data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706507762
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "micro_cf_ALL <-\n",
        "micro_cf_ALL  |>\n",
        "    # collapsing tazocin (brand name) and pip-taz (chemical name) into one\n",
        "    mutate(DRUG = case_when(\n",
        "        DRUG %in% c(\"PIPERACILLIN-TAZOBACTAM\",\"TAZOCIN\") ~ \"TAZOCIN\",\n",
        "        TRUE ~ DRUG\n",
        "    )) |>\n",
        "    # only defining classes for drugs of interest\n",
        "    mutate(DRUG_CLASS = case_when(\n",
        "        # aminoglycosides\n",
        "        DRUG %in% c(\"AMIKACIN\", \"GENTAMICIN\", \"TOBRAMYCIN\",\"NEOMYCIN\",\"SPECTINOMYCIN\",\"STREPTOMYCIN\",\"KANAMYCIN\") ~ \"Aminoglycosides\",\n",
        "        # carbapenems\n",
        "        DRUG %in% c(\"ERTAPENEM\",\"IMIPENEM\",\"MEROPENEM\") ~ \"Carbapenems\",\n",
        "        # cephalosporins\n",
        "        DRUG %in% c(\"CEFEPIME\", \"CEFIDEROCOL\", \"CEFIXIME\", \"CEFOTAXIME\", \"CEFOXITIN\", \"CEFPODOXIME\", \"CEFTAZIDIME\", \"CEFTAZIDIME-AVIBACTAM\", \"CEFTAROLINE\", \"CEFTOLOZANE-TAZOBACTAM\",\"CEFTRIAXONE\",\"CEFUROXIME\",\"CEPHALEXIN\") ~ \"Cephalosporins\",\n",
        "        # fluoroquinolones\n",
        "        DRUG %in% c(\"CIPROFLOXACIN\",\"LEVOFLOXACIN\",\"NORFLOXACIN\", \"OFLOXACIN\",\"MOXIFLOXACIN\",\"PEFLOXACIN\",\"QUINOLONE\",\"NALIDIXIC ACID\") ~ \"Fluoroquinolones\",\n",
        "        # monobactams\n",
        "        DRUG %in% c(\"AZTREONAM\") ~ \"Monobactams\",\n",
        "        # penicillins\n",
        "        DRUG %in% c(\"AMOXYCILLIN\",\"AUGMENTIN\",\"CO-AMOXICLAV\",\"TICARCILLIN-CLAVULANATE\",\"FLUCLOXACILLIN\",\"TAZOCIN\",\"TEMOCILLIN\",\"PENICILLIN\") ~ \"Penicillins\",\n",
        "        #macrolides\n",
        "        DRUG %in% c(\"AZITHROMYCIN\",\"CLARITHROMYCIN\",\"ERYTHROMYCIN\") ~ \"Macrolides\",\n",
        "        # sulfonamides\n",
        "        DRUG %in% c(\"COTRIMOXAZOLE\") ~ \"Sulfonamides\",\n",
        "        # other\n",
        "        TRUE ~ \"Other\",\n",
        "    ))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "### blood cultures only susceptibility testing data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706512491
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "micro_cf_BLOOD <-\n",
        "micro_cf_BLOOD |>\n",
        "    # collapsing tazocin (brand name) and pip-taz (chemical name) into one\n",
        "    mutate(DRUG = case_when(\n",
        "        DRUG %in% c(\"PIPERACILLIN-TAZOBACTAM\",\"TAZOCIN\") ~ \"TAZOCIN\",\n",
        "        TRUE ~ DRUG\n",
        "    )) |>\n",
        "    # only defining classes for drugs of interest\n",
        "    mutate(DRUG_CLASS = case_when(\n",
        "        # aminoglycosides\n",
        "        DRUG %in% c(\"AMIKACIN\", \"GENTAMICIN\", \"TOBRAMYCIN\",\"NEOMYCIN\",\"SPECTINOMYCIN\",\"STREPTOMYCIN\",\"KANAMYCIN\") ~ \"Aminoglycosides\",\n",
        "        # carbapenems\n",
        "        DRUG %in% c(\"ERTAPENEM\",\"IMIPENEM\",\"MEROPENEM\") ~ \"Carbapenems\",\n",
        "        # cephalosporins\n",
        "        DRUG %in% c(\"CEFEPIME\", \"CEFIDEROCOL\", \"CEFIXIME\", \"CEFOTAXIME\", \"CEFOXITIN\", \"CEFPODOXIME\", \"CEFTAZIDIME\", \"CEFTAZIDIME-AVIBACTAM\", \"CEFTAROLINE\", \"CEFTOLOZANE-TAZOBACTAM\",\"CEFTRIAXONE\",\"CEFUROXIME\",\"CEPHALEXIN\") ~ \"Cephalosporins\",\n",
        "        # fluoroquinolones\n",
        "        DRUG %in% c(\"CIPROFLOXACIN\",\"LEVOFLOXACIN\",\"NORFLOXACIN\", \"OFLOXACIN\",\"MOXIFLOXACIN\",\"PEFLOXACIN\",\"QUINOLONE\",\"NALIDIXIC ACID\") ~ \"Fluoroquinolones\",\n",
        "        # monobactams\n",
        "        DRUG %in% c(\"AZTREONAM\") ~ \"Monobactams\",\n",
        "        # penicillins\n",
        "        DRUG %in% c(\"AMOXYCILLIN\",\"AUGMENTIN\",\"CO-AMOXICLAV\",\"PIPERACILLIN-TAZOBACTAM\",\"TICARCILLIN-CLAVULANATE\",\"FLUCLOXACILLIN\",\"TAZOCIN\",\"TEMOCILLIN\",\"PENICILLIN\") ~ \"Penicillins\",\n",
        "        #macrolides\n",
        "        DRUG %in% c(\"AZITHROMYCIN\",\"CLARITHROMYCIN\",\"ERYTHROMYCIN\") ~ \"Macrolides\",\n",
        "        # sulfonamides\n",
        "        DRUG %in% c(\"COTRIMOXAZOLE\") ~ \"Sulfonamides\",\n",
        "        # other\n",
        "        TRUE ~ \"Other\",\n",
        "    ))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# joining demographics data, episodes data, & microbiology data\n",
        "\n",
        "## creating all_data (can take ~5 mins to run)\n",
        "\n",
        "### 1. joining demographics data & episodes data\n",
        "\n",
        "### 2. performing join with all microbiology susceptibility testing data and filtering where the following conditions are met:\n",
        "\n",
        "###   SAMPLE_COLLECTED_DT >= ADMISSION_DATE & SAMPLE_COLLECTED_DT <= DISCHARGE_DATE"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706584220
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "all_data <- \n",
        "episodes_cf |>\n",
        "    # performing join\n",
        "    left_join(demographics_cf,\n",
        "        by = \"SUBJECT\") |>\n",
        "    # replacing NA values resulting from join\n",
        "    mutate(across(c(BIRTH_DATE:GENDER_DESC), ~replace_na(.x, \"No Data\"))) |>\n",
        "    # relocating demographics columns\n",
        "    relocate(colnames(demographics_cf), .before = \"SPELL_IDENTIFIER\") |>\n",
        "    # performing left join with micro data\n",
        "    left_join(micro_cf_ALL,\n",
        "        by = \"SUBJECT\",\n",
        "        relationship = \"many-to-many\") |>\n",
        "    # marking difference where the following conditions are met:\n",
        "        # 1. SAMPLE_COLLECTED_DT >= ADMISSION_DATE\n",
        "        # 2. SAMPLE_COLLECTED_DT <= DISCHARGE_DATE\n",
        "    mutate(WITHIN_SPELL = if_else(\n",
        "            SAMPLE_COLLECTED_DT >= ADMISSION_DATE &\n",
        "            SAMPLE_COLLECTED_DT <= DISCHARGE_DATE, TRUE, FALSE)) |>\n",
        "    # removing unwanted episodes data\n",
        "    filter(WITHIN_SPELL == TRUE)\n",
        "\n",
        "head(all_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## checking joins makes sense"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706589947
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "print(\"The number of rows in the episodes data:\")\n",
        "length(episodes_cf$SUBJECT)\n",
        "print(\"The number of distinct patients for which we have episodes data (1 patient can have more than 1 spell or episode):\")\n",
        "n_distinct(episodes_cf$SUBJECT)\n",
        "\n",
        "print(\"The number of rows in the microbiology susceptibiltiy testing data:\")\n",
        "length(micro_cf_ALL$SUBJECT)\n",
        "print(\"The number of distinct patients for which we have microbiology susceptibiltiy testing data (1 patient can have many cultures taken from many different spells or episodes):\")\n",
        "n_distinct(micro_cf_ALL$SUBJECT)\n",
        "\n",
        "print(\"The number of rows in the joined data:\")\n",
        "length(all_data$SUBJECT)\n",
        "print(\"The number of distinct patients for which we have matching episodes data and microbiology. That is, the patient was sampled whilst admitted to hospital:\")\n",
        "n_distinct(all_data$SUBJECT)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## final tidying steps"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706606318
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "all_data <-\n",
        "all_data |>\n",
        "    # identifying which isolates were collected 48hrs after admission\n",
        "    mutate(AFTER_48HRS = if_else(SAMPLE_COLLECTED_DT > (ADMISSION_DATE + 2) & SAMPLE_COLLECTED_DT <= DISCHARGE_DATE, \"Collection after 48 hours of admission\", \"Collection within 48 hours of admission\")) |>\n",
        "    # reodering levels\n",
        "    mutate(AFTER_48HRS = fct_relevel(AFTER_48HRS, \"Collection after 48 hours of admission\", \"Collection within 48 hours of admission\")) |>\n",
        "    # defining cut-off date for discharge date - so no patients still in hospital are included\n",
        "    filter(DISCHARGE_DATE <= ymd(\"2025-01-01\"))\n",
        "\n",
        "head(all_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## creating bld_data\n",
        "\n",
        "### 1. joining demographics data & episodes data\n",
        "\n",
        "### 2. performing join with blood culture only susceptibility testing data and filtering where the following conditions are met:\n",
        "\n",
        "###   SAMPLE_COLLECTED_DT >= ADMISSION_DATE & SAMPLE_COLLECTED_DT <= DISCHARGE_DATE"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706626252
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "bld_data <- \n",
        "episodes_cf |>\n",
        "    # performing join\n",
        "    left_join(demographics_cf,\n",
        "        by = \"SUBJECT\") |>\n",
        "    # replacing NA values resulting from join\n",
        "    mutate(across(c(BIRTH_DATE:GENDER_DESC), ~replace_na(.x, \"No Data\"))) |>\n",
        "    # relocating demographics columns\n",
        "    relocate(colnames(demographics_cf), .before = \"SPELL_IDENTIFIER\") |>\n",
        "    # performing left join with blood cultures only data\n",
        "    left_join(micro_cf_BLOOD,\n",
        "        by = \"SUBJECT\",\n",
        "        relationship = \"many-to-many\") |>\n",
        "    # marking difference where the following conditions are met:\n",
        "        # 1. SAMPLE_COLLECTED_DT >= ADMISSION_DATE\n",
        "        # 2. SAMPLE_COLLECTED_DT <= DISCHARGE_DATE\n",
        "    mutate(WITHIN_SPELL = if_else(\n",
        "            SAMPLE_COLLECTED_DT >= ADMISSION_DATE &\n",
        "            SAMPLE_COLLECTED_DT <= DISCHARGE_DATE, TRUE, FALSE)) |>\n",
        "    # removing unwanted episodes data\n",
        "    filter(WITHIN_SPELL == TRUE)\n",
        "\n",
        "head(bld_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## checking joings make sense"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706631053
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "print(\"The number of rows in the episodes data:\")\n",
        "length(episodes_cf$SUBJECT)\n",
        "print(\"The number of distinct patients for which we have episodes data (1 patient can have more than 1 spell or episode):\")\n",
        "n_distinct(episodes_cf$SUBJECT)\n",
        "\n",
        "print(\"The number of rows in the blood cultures only susceptibiltiy testing data:\")\n",
        "length(micro_cf_BLOOD$SUBJECT)\n",
        "print(\"The number of distinct patients for which we have blood cultures only susceptibiltiy testing data (1 patient can have many cultures taken from many different spells or episodes):\")\n",
        "n_distinct(micro_cf_BLOOD$SUBJECT)\n",
        "\n",
        "print(\"The number of rows in the joined data:\")\n",
        "length(bld_data$SUBJECT)\n",
        "print(\"The number of distinct patients for which we have matching episodes data and  blood cultures only susceptibiltiy testing data. That is, the patient was sampled whilst admitted to hospital:\")\n",
        "n_distinct(bld_data$SUBJECT)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## final tidying steps"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# **<<< 2. LOADING WORKSPACE >>>** "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1744706636122
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "bld_data <-\n",
        "bld_data |>\n",
        "    # identifying which isolates were collected 48hrs after admission\n",
        "    mutate(AFTER_48HRS = if_else(SAMPLE_COLLECTED_DT > (ADMISSION_DATE + 2) & SAMPLE_COLLECTED_DT <= DISCHARGE_DATE, \"Collection after 48 hours of admission\", \"Collection within 48 hours of admission\")) |>\n",
        "    # reodering levels\n",
        "    mutate(AFTER_48HRS = fct_relevel(AFTER_48HRS, \"Collection after 48 hours of admission\", \"Collection within 48 hours of admission\")) |>\n",
        "    # defining cut-off date for discharge date - so no patients still in hospital are included\n",
        "    filter(DISCHARGE_DATE <= ymd(\"2025-01-01\"))\n",
        "\n",
        "head(bld_data)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754565166118
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "load(\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/09052025.RData\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# saving workspace\n",
        "## last saved: 29042025"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754385796470
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "ls()\n",
        "## BE CAREFUL NOT TO RUN THE BELOW WHEN INAPPROPRIATE\n",
        "#save.image(\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/X.RData\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# checking numbers for thesis"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1749219563658
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "n_distinct(micro_cf_ALL)\n",
        "n_distinct(micro_cf_ALL$SUBJECT)\n",
        "n_distinct(micro_cf_BLOOD)\n",
        "n_distinct(micro_cf_BLOOD$SUBJECT)\n",
        "n_distinct(all_data$SUBJECT)\n",
        "n_distinct(bld_data$SUBJECT)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# **<<< 3. PLOTTING >>>**\n",
        "\n",
        "# **exact plotting dimensions to be determined before final export, but all plots ready to be considered for final export in \"/checked&ready/\" directory**\n",
        "\n",
        "## **micro_cf_ALL** : all microbiology susceptibility testing data\n",
        "## **micro_cf_BLOOD** : microbiology susceptibility testing data attributed to blood cultures only\n",
        "## **all_data** : all microbiology susceptibility testing data joined with available & matching episodes/demographics data\n",
        "## **bld_data** : microbiology susceptibility testing data attributed to blood cultures only joined with available & matching episodes/demographics data\n",
        "\n",
        "# identifying end date cut off that make sense for plotting"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1745855800852
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "micro_cf_ALL |>\n",
        "# filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  select(SUBJECT,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         ORGANISM_OR_BUG) |>\n",
        "  distinct() |>\n",
        "  # creating month column\n",
        "  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\")) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(MONTH < \"2025-04-01\") |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(\n",
        "    ORGANISM_OR_BUG,\n",
        "    MONTH\n",
        "  ) |>\n",
        "  tally() |>\n",
        "  arrange(n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## filter(MONTH < \"2025-04-01\") works well as months before April 2025 represent complete collection months"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1746791385224
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "end_date <- as.Date(\"2025-04-01\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# bug counts and proportions: microbiology data\n",
        "\n",
        "## 1. line chart **CHECKED & READY**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754565206583
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# line chart\n",
        "#micro_cf_ALL |>\n",
        "micro_cf_BLOOD |>\n",
        "# filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  select(SUBJECT,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         ORGANISM_OR_BUG) |>\n",
        "  distinct() |>\n",
        "  # creating month column\n",
        "  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\")) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(MONTH < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(\n",
        "    ORGANISM_OR_BUG,\n",
        "    MONTH\n",
        "  ) |>\n",
        "  tally() |>\n",
        "ggplot(aes(x=MONTH,\n",
        "           y=n,\n",
        "           colour=ORGANISM_OR_BUG)) +\n",
        "  geom_line(alpha=0.8) +\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # second national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Isolate Count\",\n",
        "       colour = \"Organism\") +\n",
        "  theme_bw() +\n",
        "  scale_colour_manual(values = c(\"#008080\",\n",
        "                                 \"#FFA500\",                               \n",
        "                                 \"#ea705d\",\n",
        "                                 \"#71c9dd\",\n",
        "                                 \"#33b29f\",\n",
        "                                 \"#6376a0\",\n",
        "                                 \"#f5af98\",\n",
        "                                 \"#9da6c3\",\n",
        "                                 \"#a6dace\")) +\n",
        "  # sizing\n",
        "  theme(axis.title.x = element_text(vjust = -2),\n",
        "        axis.title.y = element_text(vjust = 2),\n",
        "        # add legend box\n",
        "        legend.background=element_blank(),\n",
        "        # legend text\n",
        "        legend.text = element_text(size=11,face = \"italic\"), \n",
        "        # ensuring even legend border\n",
        "        legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "        legend.box.background=element_rect(colour = \"black\"),\n",
        "        legend.title = element_text(size=11))\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/1_micro_cf_ALL_bug_counts_line_chart_GTG.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/1_micro_cf_BLOOD_bug_counts_line_chart_GTG.jpeg\",\n",
        "       #height= 5,\n",
        "       #width=10)\n",
        "\n",
        "png(\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/1_micro_cf_ALL_bug_counts.jpeg\",\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/1_micro_cf_BLOOD_bug_counts.jpeg\",\n",
        "       width=8,\n",
        "       height=3,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## 2. proportions chart **CHECKED & READY**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754390218339
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# proportions chart\n",
        "#micro_cf_ALL |>\n",
        "micro_cf_BLOOD |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  select(SUBJECT,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         ORGANISM_OR_BUG) |>\n",
        "  distinct() |>\n",
        "  # creating month column\n",
        "  mutate(month=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\")) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(month < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(\n",
        "    ORGANISM_OR_BUG,\n",
        "    month\n",
        "  ) |>\n",
        "  summarise(total = n()) |>\n",
        "  ungroup() |>\n",
        "  group_by(month) |>\n",
        "  mutate(prop = total / sum(total)) |>\n",
        "  ggplot(aes(x=month,\n",
        "             y=prop,\n",
        "             fill=ORGANISM_OR_BUG)) +\n",
        "  geom_bar(stat=\"identity\",alpha=0.8) +\n",
        "  scale_y_continuous(labels = function(x){paste0(x*100,\"%\")}) +\n",
        "  theme_bw() +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Proportion (%)\",\n",
        "       fill = \"Organism\") +\n",
        "  theme_bw() +\n",
        "  scale_fill_manual(values = c(\"#008080\",\n",
        "                               \"#FFA500\",                               \n",
        "                               \"#ea705d\",\n",
        "                               \"#71c9dd\",\n",
        "                               \"#33b29f\",\n",
        "                               \"#6376a0\",\n",
        "                               \"#f5af98\",\n",
        "                               \"#9da6c3\",\n",
        "                               \"#a6dace\")) +\n",
        "  # sizing\n",
        "  theme(axis.title.x = element_text(vjust = -2),\n",
        "        axis.title.y = element_text(vjust = 2),\n",
        "        # add legend box\n",
        "        legend.background=element_blank(),\n",
        "        # legend text\n",
        "        legend.text = element_text(size=11,face = \"italic\"), \n",
        "        # ensuring even legend border\n",
        "        legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "        legend.box.background=element_rect(colour = \"black\"),\n",
        "        legend.title = element_text(size=11)) +\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # second national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8)\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/2_micro_cf_ALL_bug_proportions_line_chart_GTG.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/2_micro_cf_BLOOD_bug_proportions_line_chart_GTG.jpeg\",\n",
        "       #height= 5,\n",
        "       #width=10)\n",
        "\n",
        "png(\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/1_micro_cf_ALL_bug_proportions.jpeg\",\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/1_micro_cf_BLOOD_bug_proportions.jpeg\",\n",
        "       width=8,\n",
        "       height=3,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting bug counts and proportions: all_data, bld_data\n",
        "\n",
        "## 3. line chart **CHECKED & READY**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1745856147616
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# line chart\n",
        "all_data |>\n",
        "#bld_data |>\n",
        "# filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  select(SUBJECT,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         ORGANISM_OR_BUG) |>\n",
        "  distinct() |>\n",
        "  # creating month column\n",
        "  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\")) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(MONTH < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(\n",
        "    ORGANISM_OR_BUG,\n",
        "    MONTH\n",
        "  ) |>\n",
        "  tally() |>\n",
        "ggplot(aes(x=MONTH,\n",
        "           y=n,\n",
        "           colour=ORGANISM_OR_BUG)) +\n",
        "  geom_line(alpha=0.8) +\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) +\n",
        "  # second national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Count\",\n",
        "       colour = \"Organism\") +\n",
        "  theme_bw() +\n",
        "  scale_colour_manual(values = c(\"#008080\",\n",
        "                                 \"#FFA500\",                               \n",
        "                                 \"#ea705d\",\n",
        "                                 \"#71c9dd\",\n",
        "                                 \"#33b29f\",\n",
        "                                 \"#6376a0\",\n",
        "                                 \"#f5af98\",\n",
        "                                 \"#9da6c3\",\n",
        "                                 \"#a6dace\")) +\n",
        "  # sizing\n",
        "  theme(axis.title.x = element_text(vjust = -2),\n",
        "        axis.title.y = element_text(vjust = 2),\n",
        "        # add legend box\n",
        "        legend.background=element_blank(),\n",
        "        # legend text\n",
        "        legend.text = element_text(size=11,face = \"italic\"), \n",
        "        # ensuring even legend border\n",
        "        legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "        legend.box.background=element_rect(colour = \"black\"),\n",
        "        legend.title = element_text(size=11))\n",
        "\n",
        "ggsave(plot=last_plot(),\n",
        "       \"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/3_all_data_bug_counts_line_chart_GTG.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/3_bld_data_bug_counts_line_chart_GTG.jpeg\",\n",
        "       height= 5,\n",
        "       width=10)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## 4. proportions chart  **CHECKED & READY**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1745856193662
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# proportions chart\n",
        "all_data |>\n",
        "#bld_data |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  select(SUBJECT,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         ORGANISM_OR_BUG) |>\n",
        "  distinct() |>\n",
        "  # creating month column\n",
        "  mutate(month=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\")) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(month < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(\n",
        "    ORGANISM_OR_BUG,\n",
        "    month\n",
        "  ) |>\n",
        "  summarise(total = n()) |>\n",
        "  ungroup() |>\n",
        "  group_by(month) |>\n",
        "  mutate(prop = total / sum(total)) |>\n",
        "  ggplot(aes(x=month,\n",
        "             y=prop,\n",
        "             fill=ORGANISM_OR_BUG)) +\n",
        "  geom_bar(stat=\"identity\",alpha=0.8) +\n",
        "  scale_y_continuous(labels = percent) +\n",
        "  theme_bw() +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Proportion (%)\",\n",
        "       fill = \"Organism\") +\n",
        "  theme_bw() +\n",
        "  scale_fill_manual(values = c(\"#008080\",\n",
        "                               \"#FFA500\",                               \n",
        "                               \"#ea705d\",\n",
        "                               \"#71c9dd\",\n",
        "                               \"#33b29f\",\n",
        "                               \"#6376a0\",\n",
        "                               \"#f5af98\",\n",
        "                               \"#9da6c3\",\n",
        "                               \"#a6dace\")) +\n",
        "  # sizing\n",
        "  theme(axis.title.x = element_text(vjust = -2),\n",
        "        axis.title.y = element_text(vjust = 2),\n",
        "        # add legend box\n",
        "        legend.background=element_blank(),\n",
        "        # legend text\n",
        "        legend.text = element_text(size=11,face = \"italic\"), \n",
        "        # ensuring even legend border\n",
        "        legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "        legend.box.background=element_rect(colour = \"black\"),\n",
        "        legend.title = element_text(size=11)) +\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) +\n",
        "  # second national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8)\n",
        "\n",
        "ggsave(plot=last_plot(),\n",
        "       \"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/4_all_data_bug_counts_proportions_chart_GTG.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/4_bld_data_bug_counts_proportions_chart_GTG.jpeg\",\n",
        "       height= 5,\n",
        "       width=10)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting HO infections vs CO infections counts and proportions for K. pneumoniae and E. coli: all_data, bld_data\n",
        "\n",
        "## 5. line chart **CHECKED & READY**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754565328146
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# line chart\n",
        "#all_data |>\n",
        "bld_data |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # grouping other Enterobacteriaceae in \"Other\" category\n",
        "  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c(\"Escherichia coli\",\"Klebsiella pneumoniae\"), \n",
        "         ORGANISM_OR_BUG, \"Other Enterobacteriaceae\")) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         SPELL_IDENTIFIER,\n",
        "         EPISODE_IDENTIFIER,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         WITHIN_SPELL,\n",
        "         AFTER_48HRS,\n",
        "         ORGANISM_OR_BUG) |>\n",
        "  # removing duplicates\n",
        "  distinct() |>\n",
        "  # creating month column\n",
        "  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\"),\n",
        "         # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\n",
        "            # else\n",
        "            \"Undefined\"))) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(MONTH < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(\n",
        "    ORGANISM_OR_BUG,\n",
        "    HO,\n",
        "    MONTH\n",
        "  ) |>\n",
        "  tally() |>\n",
        "  #View()\n",
        "  # plotting data\n",
        "  ggplot(aes(x=MONTH,\n",
        "             y=n,\n",
        "             colour=HO)) +\n",
        "  geom_line(alpha=0.8) +\n",
        "  # sizing\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # second national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  theme_bw() +\n",
        "  scale_colour_npg() +\n",
        "  theme(axis.title.x = element_text(vjust = -2),\n",
        "        axis.title.y = element_text(vjust = 2),\n",
        "        # add legend box\n",
        "        legend.background=element_blank(),\n",
        "        # legend text\n",
        "        strip.text = element_text(size=12,\n",
        "                                  face = \"italic\"), \n",
        "        strip.background = element_blank(),\n",
        "        # ensuring even legend border\n",
        "        legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "        legend.box.background=element_rect(colour = \"black\"),\n",
        "        legend.title = element_text(size=11)) +\n",
        "  facet_wrap(~ORGANISM_OR_BUG) +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Isolate Count\",\n",
        "       colour=\"Infection Category\")\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/2_29052025/5_all_data_HO_vs_CO_line_chart_29052025.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/2_29052025/5_bld_data_HO_vs_CO_line_chart_29052025.jpeg\",\n",
        "       #height= 3,\n",
        "       #width=8)\n",
        "\n",
        "png(\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/3_all_data_bug_counts.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/3_bld_data_bug_counts.jpeg\",\n",
        "       width=16,\n",
        "       height=3,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## 6. proportions chart **CHECKED & READY**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754391050680
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# proportions chart\n",
        "#all_data |>\n",
        "bld_data |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # grouping other Enterobacteriaceae in \"Other\" category\n",
        "  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c(\"Escherichia coli\",\"Klebsiella pneumoniae\"), \n",
        "         ORGANISM_OR_BUG, \"Other Enterobacteriaceae\")) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         SPELL_IDENTIFIER,\n",
        "         EPISODE_IDENTIFIER,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         WITHIN_SPELL,\n",
        "         AFTER_48HRS,\n",
        "         ORGANISM_OR_BUG) |>\n",
        "  # removing duplicates\n",
        "  distinct() |>\n",
        "  # creating month column\n",
        "  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\"),\n",
        "         # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\"Undefined\"))) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(MONTH < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(HO,\n",
        "           ORGANISM_OR_BUG,\n",
        "           MONTH) |>\n",
        "  summarise(total = n()) |>\n",
        "  ungroup() |>\n",
        "  group_by(MONTH,ORGANISM_OR_BUG) |>\n",
        "  mutate(prop = total / sum(total)) |>\n",
        "  #View()\n",
        "  # plotting data\n",
        "  ggplot(aes(x=MONTH,\n",
        "             y=prop,\n",
        "             fill=HO)) +\n",
        "  geom_bar(stat=\"identity\",alpha=0.8) +\n",
        "  scale_y_continuous(labels = function(x){paste0(x*100,\"%\")}) +\n",
        "  theme_bw() +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Proportion (%)\",\n",
        "       fill = \"Infection Category\") +\n",
        "  scale_fill_npg() +\n",
        "  theme(axis.title.x = element_text(vjust = -2),\n",
        "        axis.title.y = element_text(vjust = 2),\n",
        "        # add legend box\n",
        "        legend.background=element_blank(),\n",
        "        # legend text\n",
        "        strip.text = element_text(size=12,face = \"italic\"), \n",
        "        strip.background = element_blank(),\n",
        "        # ensuring even legend border\n",
        "        legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "        legend.box.background=element_rect(colour = \"black\"),\n",
        "        legend.title = element_text(size=11)) +\n",
        "  facet_wrap(~ORGANISM_OR_BUG)  +\n",
        "  # sizing\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # second national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8)\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/2_29052025/6_all_data_HO_vs_CO_proportions_chart_29052025.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/2_29052025/6_bld_data_HO_vs_CO_proportions_chart_29052025.jpeg\",\n",
        "       #height= 3,\n",
        "       #width=16)\n",
        "\n",
        "png(\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/3_all_data_bug_proportions.jpeg\",\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/3_bld_data_bug_proportions.jpeg\",\n",
        "       width=16,\n",
        "       height=3,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting HO infections vs CO infections counts and proportions for all bugs: all_data, bld_data (minus non-Enterobacteriaceae)\n",
        "\n",
        "## 7. line chart **CHECKED & READY**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754565371195
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# line chart\n",
        "#all_data |>\n",
        "bld_data |>\n",
        " # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         SPELL_IDENTIFIER,\n",
        "         EPISODE_IDENTIFIER,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         WITHIN_SPELL,\n",
        "         AFTER_48HRS,\n",
        "         ORGANISM_OR_BUG) |>\n",
        "  # removing duplicates\n",
        "  distinct() |>\n",
        "  # creating month column\n",
        "  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\"),\n",
        "         # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\n",
        "            # else\n",
        "            \"Undefined\"))) |>\n",
        "   # filtering incomplete end month\n",
        "  filter(MONTH < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(\n",
        "    ORGANISM_OR_BUG,\n",
        "    HO,\n",
        "    MONTH\n",
        "  ) |>\n",
        "  tally() |>\n",
        "   # plotting data\n",
        "  ggplot(aes(x=MONTH,\n",
        "             y=n,\n",
        "             colour=HO)) +\n",
        "  geom_line(alpha=0.8) +\n",
        "  # sizing\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # second national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  theme_bw() +\n",
        "  scale_colour_npg() +\n",
        "  theme(axis.title.x = element_text(vjust = -2),\n",
        "        axis.title.y = element_text(vjust = 2),\n",
        "        # add legend box\n",
        "        legend.background=element_blank(),\n",
        "        # legend text\n",
        "        strip.text = element_text(size=12,face = \"italic\"), \n",
        "        strip.background = element_blank(),\n",
        "        # ensuring even legend border\n",
        "        legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "        legend.box.background=element_rect(colour = \"black\"),\n",
        "        legend.title = element_text(size=11)) +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Isolate Count\",\n",
        "       colour=\"Infection Category\") +\n",
        "  facet_wrap(~ORGANISM_OR_BUG)\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/7_all_data_HO_vs_CO_line_chart_v2_GTG.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/7_bld_data_HO_vs_CO_line_chart_v2_GTG.jpeg\",\n",
        "       #height= 9,\n",
        "       #width=16)\n",
        "\n",
        "png(\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/4_all_data_bug_counts_alternate.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/4_bld_data_bug_counts_alternate.jpeg\",\n",
        "       width=16,\n",
        "       height=9,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## 8. proportions chart **CHECKED & READY**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754391552653
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# proportions chart\n",
        "#all_data |>\n",
        "bld_data |>\n",
        "# filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         SPELL_IDENTIFIER,\n",
        "         EPISODE_IDENTIFIER,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         WITHIN_SPELL,\n",
        "         AFTER_48HRS,\n",
        "         ORGANISM_OR_BUG) |>\n",
        "  # removing duplicates\n",
        "  distinct() |>\n",
        "  # creating month column\n",
        "  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\"),\n",
        "         # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\"Undefined\"))) |>\n",
        "   # filtering incomplete end month\n",
        "  filter(MONTH < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(HO,\n",
        "           ORGANISM_OR_BUG,\n",
        "           MONTH) |>\n",
        "  summarise(total = n()) |>\n",
        "  ungroup() |>\n",
        "  group_by(MONTH,ORGANISM_OR_BUG) |>\n",
        "  mutate(prop = total / sum(total)) |>\n",
        "  #View()\n",
        "  # plotting data\n",
        "  ggplot(aes(x=MONTH,\n",
        "             y=prop,\n",
        "             fill=HO)) +\n",
        "  geom_bar(stat=\"identity\",alpha=0.8) +\n",
        "  scale_y_continuous(labels = function(x){paste0(x*100,\"%\")}) +\n",
        "  theme_bw() +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Proportion (%)\",\n",
        "       fill = \"Infection Category\") +\n",
        "  scale_fill_npg() +\n",
        "  theme(axis.title.x = element_text(vjust = -2),\n",
        "        axis.title.y = element_text(vjust = 2),\n",
        "        # add legend box\n",
        "        legend.background=element_blank(),\n",
        "        # legend text\n",
        "        strip.text = element_text(size=12,face = \"italic\"), \n",
        "        strip.background = element_blank(),\n",
        "        # ensuring even legend border\n",
        "        legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "        legend.box.background=element_rect(colour = \"black\"),\n",
        "        legend.title = element_text(size=11)) +\n",
        "  facet_wrap(~ORGANISM_OR_BUG) +\n",
        "  # sizing\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # second national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8)\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/8_all_data_HO_vs_CO_proportions_chart_v2_GTG.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/8_bld_data_HO_vs_CO_proportions_chart_v2_GTG.jpeg\",\n",
        "       #height= 9,\n",
        "       #width=16)\n",
        "\n",
        "png(\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/4_all_data_bug_proportions_alternate.jpeg\",\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/4_bld_data_bug_proportions_alternate.jpeg\",\n",
        "       width=16,\n",
        "       height=9,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting bug proportions across HO vs CO infections: all_data, bld_data\n",
        "\n",
        "## 9. proportions chart"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754391839211
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# proportions chart\n",
        "#all_data |>\n",
        "bld_data |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  select(SUBJECT,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         ORGANISM_OR_BUG,\n",
        "         WITHIN_SPELL,\n",
        "         AFTER_48HRS) |>\n",
        "  distinct() |>\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           AFTER_48HRS) |>\n",
        "  filter(n()>5) |>\n",
        "  ungroup() |>\n",
        "  # creating month column\n",
        "  mutate(month=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\"),\n",
        "         # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\"Undefined\"))) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(month < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(\n",
        "    ORGANISM_OR_BUG,\n",
        "    HO,\n",
        "    month\n",
        "  ) |>\n",
        "  summarise(total = n()) |>\n",
        "  ungroup() |>\n",
        "  group_by(HO,month) |>\n",
        "  mutate(prop = total / sum(total)) |>\n",
        "  ggplot(aes(x=month,\n",
        "             y=prop,\n",
        "             fill=ORGANISM_OR_BUG)) +\n",
        "  geom_bar(stat=\"identity\",alpha=0.8) +\n",
        "  scale_y_continuous(labels = function(x){paste0(x*100,\"%\")}) +\n",
        "  theme_bw() +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Proportion (%)\",\n",
        "       fill = \"Organism\") +\n",
        "  theme_bw() +\n",
        "  scale_fill_manual(values = c(\"#008080\",\n",
        "                               \"#FFA500\",                               \n",
        "                               \"#ea705d\",\n",
        "                               \"#71c9dd\",\n",
        "                               \"#33b29f\",\n",
        "                               \"#6376a0\",\n",
        "                               \"#f5af98\",\n",
        "                               \"#9da6c3\",\n",
        "                               \"#a6dace\")) +\n",
        "  # sizing\n",
        "  theme(axis.title.x = element_text(vjust = -2),\n",
        "        axis.title.y = element_text(vjust = 2),\n",
        "        # add legend box\n",
        "        strip.text = element_text(size=12), \n",
        "        strip.background = element_blank(),\n",
        "        legend.background=element_blank(),\n",
        "        # legend text\n",
        "        legend.text = element_text(size=11,face = \"italic\"), \n",
        "        # ensuring even legend border\n",
        "        legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "        legend.box.background=element_rect(colour = \"black\"),\n",
        "        legend.title = element_text(size=11)) +\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # second national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  facet_wrap(~HO)\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/9_all_data_HO_vs_CO_proportions_chart_v3_GTG.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/1_12052025_aka_GTG/9_bld_data_HO_vs_CO_proportions_chart_v3_GTG.jpeg\",\n",
        "       #height= 3,\n",
        "       #width=10.6)\n",
        "\n",
        "png(\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/5_all_data_bug_proportions_alternate2.jpeg\",\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/5_bld_data_bug_proportions_alternate2.jpeg\",\n",
        "       width=10.6,\n",
        "       height=3,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting E. coli and K. pneumoniae monthly resistance rates selected drugs\n",
        "\n",
        "## 10a. line chart: all microbiology susceptibility testing data (micro_cf_All & micro_cf_BLOOD)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751130583701
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# defining breaks for marker sizes\n",
        "breaks<-c(5,10,20,50,100,200,400,800,Inf)\n",
        "#reordering drugs panels to match x axis order of first resistance plot\n",
        "drugs_order <- c(\"Amikacin\", \"Gentamicin\", \"Ertapenem\", \"Meropenem\", \"Ceftazidime\", \"Ceftriaxone\",\"Ciprofloxacin\",\"Amoxycillin\",\"Co-Amoxiclav\",\"Tazocin\",\"Temocillin\",\"Cotrimoxazole\")\n",
        "\n",
        "# line chart\n",
        "micro_cf_ALL |>\n",
        "#micro_cf_BLOOD |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # grouping other Enterobacteriaceae in \"Other\" category\n",
        "  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c(\"Escherichia coli\",\"Klebsiella pneumoniae\"), \n",
        "         ORGANISM_OR_BUG, \"Other Enterobacteriaceae\")) |>\n",
        "  # filtering for drugs of interest (defined in 4. GLMM)\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         ORGANISM_OR_BUG,\n",
        "         DRUG,\n",
        "         DRUG_CLASS,\n",
        "         DECODED) |>\n",
        "  # creating time column\n",
        "  mutate(\n",
        "       time=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\")\n",
        "       #time=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"quarter\")\n",
        "       ) |>\n",
        "  # filtering incomplete end time\n",
        "  filter(time < end_date) |>\n",
        "  # counting total bugs-drug combinations per time\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           time,\n",
        "           DRUG) |>\n",
        "  # creating total timely count column\n",
        "  mutate(timely_total=n()) |>\n",
        "  ungroup() |>\n",
        "  # creating non-susceptible column\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           time,\n",
        "           DRUG) |>\n",
        "  summarise(DECODED,\n",
        "            timely_total,\n",
        "            timely_resistant = sum(DECODED == \"Resistant\" |\n",
        "                                      DECODED == \"Intermediate\", na.rm = TRUE)) |>\n",
        "  mutate(nonsusceptible=(timely_resistant/timely_total)) |>\n",
        "  ungroup() |>\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           DRUG,\n",
        "           time) |>\n",
        "  # selecting data for times with bug-drug combinations > 5\n",
        "  filter(n()>5) |>\n",
        "  ungroup() |>\n",
        "  # adding levels for counts of total bug-drug combinations per time\n",
        "  mutate(total_levels=as.factor(cut(timely_total, breaks = breaks))) |>\n",
        "  distinct() |>  \n",
        "  # left joining with drug classes\n",
        "  left_join(\n",
        "       #micro_cf_ALL |>\n",
        "       micro_cf_BLOOD |>\n",
        "            select(DRUG,\n",
        "                   DRUG_CLASS) |>\n",
        "            distinct(),\n",
        "            by = \"DRUG\") |>\n",
        "  mutate(DRUG = str_to_title(DRUG))  |>\n",
        "  # removing duplicate rows\n",
        "  select(ORGANISM_OR_BUG,\n",
        "         time,\n",
        "         DRUG,\n",
        "         timely_total,\n",
        "         nonsusceptible,\n",
        "         total_levels) |>\n",
        "  distinct()|>\n",
        "  # reordering drugs panels to match x axis order of first resistance plot\n",
        "  mutate(DRUG = factor(DRUG, levels = drugs_order)) |>\n",
        "#View(),\n",
        "  # plotting\n",
        "  ggplot(aes(x=time,\n",
        "             y=nonsusceptible,\n",
        "             colour=ORGANISM_OR_BUG)) +\n",
        "  #geom_point(aes(size=timely_total),\n",
        "             #alpha=0.8) +\n",
        "  geom_line(alpha=0.8) +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Resistance (%)\",\n",
        "       colour = \"Organism\",\n",
        "       size = \"Quarterly Count\") +\n",
        "  theme_bw() +\n",
        "  theme(\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # legend text\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11),\n",
        "          strip.background = element_blank()\n",
        "       ) +\n",
        "  facet_wrap(~DRUG) +\n",
        "  scale_colour_manual(values = c(\"#008080\",\"#FFA500\",\"#708090\"),\n",
        "                     # making bug names italic\n",
        "                     labels = c(expression(italic(\"Escherichia coli\")),\n",
        "                                expression(italic(\"Klebsiella pneumoniae\")),\n",
        "                                expression(italic(\"Other Enterobacteriaceae\")))) +\n",
        "  scale_size_binned(breaks = breaks,\n",
        "                    range = c(0.5, 4)) +\n",
        "  scale_y_continuous(labels = scales::percent_format(accuracy = 1))+\n",
        "  guides(colour = guide_legend(order = 1)) +\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) #+\n",
        "  # second national lockdown date\n",
        "  #geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             #linetype = \"dashed\",\n",
        "             #color = \"grey\",\n",
        "             #alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  #geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             #linetype = \"dashed\",\n",
        "             #color = \"grey\",\n",
        "             #alpha=0.8)\n",
        "\n",
        "png(\n",
        "       \"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10a_micro_cf_ALL_resistance_line_chart.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10a_micro_cf_BLOOD_resistance_line_chart.jpeg\",\n",
        "       width=30,\n",
        "       height=11.7,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## 10b. line chart: all_data, bld_data\n",
        "### HO vs CO, Kpn or Ec only"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751129881028
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# line chart\n",
        "#all_data |>\n",
        "bld_data |>\n",
        "  # filtering for bug of interest\n",
        "  filter(\n",
        "        ORGANISM_OR_BUG==\"Escherichia coli\" #|\n",
        "        #ORGANISM_OR_BUG==\"Klebsiella pneumoniae\"\n",
        "        ) |>\n",
        "  # filtering for drugs of interest (defined in 4. GLMM)\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         ORGANISM_OR_BUG,\n",
        "         WITHIN_SPELL,\n",
        "         AFTER_48HRS,\n",
        "         DRUG,\n",
        "         DRUG_CLASS,\n",
        "         DECODED) |>\n",
        "  # creating time column\n",
        "  mutate(time=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\"),\n",
        "         # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\n",
        "            # else\n",
        "            \"Undefined\"))) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(time < end_date) |>\n",
        "  # counting total bugs-drug combinations per time\n",
        "  group_by(\n",
        "           #ORGANISM_OR_BUG,\n",
        "           HO,\n",
        "           time,\n",
        "           DRUG) |>\n",
        "  # creating total timely count column\n",
        "  mutate(timely_total=n()) |>\n",
        "  ungroup() |>\n",
        "  # creating non-susceptible column\n",
        "  group_by(\n",
        "           #ORGANISM_OR_BUG,\n",
        "           HO,\n",
        "           time,\n",
        "           DRUG) |>\n",
        "  summarise(DECODED,\n",
        "            timely_total,\n",
        "            timely_resistant = sum(DECODED == \"Resistant\" |\n",
        "                                      DECODED == \"Intermediate\", na.rm = TRUE)) |>\n",
        "  mutate(nonsusceptible=(timely_resistant/timely_total)) |>\n",
        "  ungroup() |>\n",
        "  group_by(\n",
        "           #ORGANISM_OR_BUG,\n",
        "           HO,\n",
        "           DRUG,\n",
        "           time) |>\n",
        "  # selecting data for times with bug-drug combinations > 5\n",
        "  filter(n()>5) |>\n",
        "  ungroup() |>\n",
        "  # adding levels for counts of total bug-drug combinations per time\n",
        "  mutate(total_levels=as.factor(cut(timely_total, breaks = breaks))) |>\n",
        "  distinct() |>  \n",
        "  # left joining with drug classes\n",
        "  left_join(\n",
        "       micro_cf_ALL |>\n",
        "       #micro_cf_BLOOD |>\n",
        "            select(DRUG,\n",
        "                   DRUG_CLASS) |>\n",
        "            distinct(),\n",
        "            by = \"DRUG\") |>\n",
        "  mutate(DRUG = str_to_title(DRUG))  |>\n",
        "  # removing duplicate rows\n",
        "  select(\n",
        "         #ORGANISM_OR_BUG,\n",
        "         HO,\n",
        "         time,\n",
        "         DRUG,\n",
        "         timely_total,\n",
        "         nonsusceptible,\n",
        "         total_levels) |>\n",
        "  distinct()|>\n",
        "  mutate(DRUG = factor(DRUG, levels = drugs_order)) |>\n",
        "#View()\n",
        "  # plotting\n",
        "  ggplot(aes(x=time,\n",
        "             y=nonsusceptible,\n",
        "             colour=HO)) +\n",
        "  #geom_point(aes(size=timely_total),\n",
        "             #alpha=0.8) +\n",
        "  geom_line(alpha=0.8) +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Resistance (%)\",\n",
        "       colour = \"Infection Category\",\n",
        "       size = \"Yearly Count\") +\n",
        "  theme_bw() +\n",
        "  theme(\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11),\n",
        "          strip.background = element_blank(),\n",
        "          # plot title\n",
        "          plot.title = element_text(hjust=0.5)\n",
        "       ) +\n",
        "  facet_wrap(~DRUG) +\n",
        "  scale_colour_npg() +\n",
        "  scale_size_binned(breaks = breaks,\n",
        "                    range = c(0.5, 4)) +\n",
        "  guides(colour = guide_legend(order = 1)) +\n",
        "  scale_y_continuous(labels = scales::percent_format(accuracy = 1))+\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) #+\n",
        "  # second national lockdown date\n",
        "  #geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             #linetype = \"dashed\",\n",
        "             #color = \"grey\",\n",
        "             #alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  #geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             #linetype = \"dashed\",\n",
        "             #color = \"grey\",\n",
        "             #alpha=0.8) +\n",
        "  #ggtitle(\"Kpn ONLY\")\n",
        "\n",
        "png(\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10b_all_data_resistance_HO_vs_CO_Kpn_ONLY_line_chart.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10b_bld_data_resistance_HO_vs_CO_Kpn_ONLY_line_chart.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10b_all_data_resistance_HO_vs_CO_Ec_ONLY_line_chart.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/10b_bld_data_resistance_HO_vs_CO_Ec_ONLY_line_chart.jpeg\",\n",
        "       width=30,\n",
        "       height=11.7,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## 11. bar chart overall resistance **CHECKED & READY**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1748949047887
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# bar chart\n",
        "micro_cf_ALL |>\n",
        "#micro_cf_BLOOD |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # grouping other Enterobacteriaceae in \"Other\" category\n",
        "  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c(\"Escherichia coli\",\"Klebsiella pneumoniae\"), \n",
        "         ORGANISM_OR_BUG, \"Other Enterobacteriaceae\")) |>\n",
        "  # filtering for drugs of interest (defined in 4. GLMM)\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         ORGANISM_OR_BUG,\n",
        "         DRUG,\n",
        "         DRUG_CLASS,\n",
        "         DECODED) |>\n",
        "  # counting total bugs-drug combinations\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           DRUG) |>\n",
        "  mutate(totalcombinations=n()) |>\n",
        "  ungroup() |>\n",
        "  # creating non-susceptible column\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           DRUG) |>\n",
        "  summarise(DECODED,\n",
        "            totalcombinations,\n",
        "            resistant = sum(DECODED == \"Resistant\" |\n",
        "                            DECODED == \"Intermediate\", na.rm = TRUE)) |>\n",
        "  distinct() |>\n",
        "  mutate(nonsusceptible=(resistant/totalcombinations)) |>\n",
        "  ungroup() |>\n",
        "  # selecting data bug-drug combinations > 5\n",
        "  filter(totalcombinations>5) |>\n",
        "  ungroup() |>\n",
        "  select(ORGANISM_OR_BUG,\n",
        "         DRUG,\n",
        "         nonsusceptible) |>\n",
        "  distinct() |>  \n",
        "  # left joining with drug classes\n",
        "  left_join(\n",
        "       #micro_cf_ALL |>\n",
        "       micro_cf_BLOOD |>\n",
        "            select(DRUG,\n",
        "                   DRUG_CLASS) |>\n",
        "            distinct(),\n",
        "            by = \"DRUG\") |>\n",
        "  # removing capitalisation of drug names\n",
        "  mutate(DRUG = str_to_title(DRUG)) |>\n",
        "  # plotting\n",
        "  ggplot(aes(x=DRUG,\n",
        "             y=nonsusceptible,\n",
        "             fill=DRUG_CLASS)) +\n",
        "  geom_col(alpha=0.8) +\n",
        "  labs(x = \"Drug\",\n",
        "       y = \"Resistance (%)\",\n",
        "       fill = \"Drug Class\",\n",
        "       size = \"Monthly Count\") +\n",
        "  theme_bw() +\n",
        "  theme(\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11, face = \"italic\"),\n",
        "          strip.background = element_blank(),\n",
        "          axis.title.x = element_text(vjust=2),\n",
        "        axis.text.x = element_text(angle=45,hjust=1)) +\n",
        "  scale_y_continuous(labels=scales::percent_format(scale=100)) +\n",
        "  facet_wrap(~ORGANISM_OR_BUG) +\n",
        "  scale_fill_aaas() +\n",
        "  scale_size_binned(breaks = breaks,\n",
        "                    range = c(0.5, 4)) +\n",
        "  guides(fill = guide_legend(order = 1)) +\n",
        "  # first national lockdown date\n",
        "  geom_hline(yintercept=0.1,\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) +\n",
        "  scale_x_discrete(limit = c(\n",
        "       \"Amikacin\",\n",
        "       \"Gentamicin\",\n",
        "       \"Ertapenem\",\n",
        "       \"Meropenem\",\n",
        "       \"Ceftazidime\",\n",
        "       \"Ceftriaxone\",\n",
        "       \"Ciprofloxacin\",\n",
        "       \"Amoxycillin\",\n",
        "       \"Co-Amoxiclav\",\n",
        "       \"Tazocin\",\n",
        "       \"Temocillin\",\n",
        "       \"Cotrimoxazole\"\n",
        "  )) +\n",
        "  scale_fill_manual(values = c(\n",
        "       \"Aminoglycosides\"=\"#3B4992CC\",\n",
        "       \"Carbapenems\"=\"#EE0000CC\",\n",
        "       \"Cephalosporins\"=\"#008B45CC\",\n",
        "       \"Fluoroquinolones\"=\"#631879CC\",\n",
        "       \"Penicillins\"=\"#5F559BCC\",\n",
        "       \"Sulfonamides\"=\"#A20056CC\"\n",
        "  ))\n",
        "\n",
        "\n",
        "ggsave(plot=last_plot(),\n",
        "       \"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/3_03062025/11_micro_cf_ALL_resistance_bar_chart_03062025.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/checked&ready/3_03062025/11_micro_cf_BLOOD_resistance_bar_chart_03062025.jpeg\",\n",
        "       height= 4,\n",
        "       width=16)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## 11. bar chart (HO vs CO)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751128895404
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# bar chart\n",
        "all_data |>\n",
        "#bld_data |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # grouping other Enterobacteriaceae in \"Other\" category\n",
        "  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c(\"Escherichia coli\",\"Klebsiella pneumoniae\"), \n",
        "         ORGANISM_OR_BUG, \"Other Enterobacteriaceae\"),\n",
        "          # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\n",
        "            # else\n",
        "            \"Undefined\"))) |>\n",
        "  # filtering for drugs of interest (defined in 4. GLMM)\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         ORGANISM_OR_BUG,\n",
        "         DRUG,\n",
        "         HO,\n",
        "         DECODED) |>\n",
        "  # counting total bugs-drug combinations\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           DRUG,\n",
        "           HO) |>\n",
        "  mutate(totalcombinations=n()) |>\n",
        "  ungroup() |>\n",
        "  # creating non-susceptible column\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           DRUG,\n",
        "           HO) |>\n",
        "  summarise(DECODED,\n",
        "            totalcombinations,\n",
        "            resistant = sum(DECODED == \"Resistant\" |\n",
        "                            DECODED == \"Intermediate\", na.rm = TRUE)) |>\n",
        "  distinct() |>\n",
        "  mutate(nonsusceptible=(resistant/totalcombinations)) |>\n",
        "  ungroup() |>\n",
        "  # selecting data bug-drug combinations > 5\n",
        "  filter(totalcombinations>5) |>\n",
        "  ungroup() |>\n",
        "  select(ORGANISM_OR_BUG,\n",
        "         DRUG,\n",
        "         HO,\n",
        "         nonsusceptible) |>\n",
        "  distinct() |>\n",
        "  # removing capitalisation of drug names\n",
        "  mutate(DRUG = str_to_title(DRUG)) |>\n",
        "  # plotting\n",
        "  ggplot(aes(x=DRUG,\n",
        "             y=nonsusceptible,\n",
        "             fill=HO)) +\n",
        "  geom_col(alpha=0.8, position = \"dodge\") +\n",
        "  labs(x = \"Drug\",\n",
        "       y = \"Resistance (%)\",\n",
        "       fill = \"Infection Category\",\n",
        "       size = \"Monthly Count\") +\n",
        "  theme_bw() +\n",
        "  theme(\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11, face = \"italic\"),\n",
        "          strip.background = element_blank(),\n",
        "          axis.title.x = element_text(vjust=2),\n",
        "        axis.text.x = element_text(angle=45,hjust=1)) +\n",
        "  scale_y_continuous(labels=scales::percent_format(scale=100)) +\n",
        "  facet_wrap(~ORGANISM_OR_BUG) +\n",
        "  scale_fill_aaas() +\n",
        "  scale_size_binned(breaks = breaks,\n",
        "                    range = c(0.5, 4)) +\n",
        "  guides(fill = guide_legend(order = 1)) +\n",
        "  # first national lockdown date\n",
        "  geom_hline(yintercept=0.1,\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) +\n",
        "  scale_x_discrete(limit = c(\n",
        "       \"Amikacin\",\n",
        "       \"Gentamicin\",\n",
        "       \"Ertapenem\",\n",
        "       \"Meropenem\",\n",
        "       \"Ceftazidime\",\n",
        "       \"Ceftriaxone\",\n",
        "       \"Ciprofloxacin\",\n",
        "       \"Amoxycillin\",\n",
        "       \"Co-Amoxiclav\",\n",
        "       \"Tazocin\",\n",
        "       \"Temocillin\",\n",
        "       \"Cotrimoxazole\"\n",
        "  )) +\n",
        "  scale_fill_npg()\n",
        "\n",
        "png(\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/11_micro_cf_ALL_resistance_HO_vs_CO_bar_chart_03062025.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/11_micro_cf_BLOOD_resistance_HO_vs_CO_bar_chart.jpeg\",\n",
        "       width=16,\n",
        "       height=4,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## 11. bar chart (Kpn blood isolates, April 2020 - December 2021)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751267904397
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# bar chart\n",
        "micro_cf_BLOOD |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG == \"Klebsiella pneumoniae\") |>\n",
        "  # filtering for drugs of interest (defined in 4. GLMM)\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # filtering for April 2020 - December 2021\n",
        "  filter(SAMPLE_COLLECTED_DT >= as.Date(\"2020-04-01\") & SAMPLE_COLLECTED_DT <= as.Date(\"2021-12-31\")) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         ORGANISM_OR_BUG,\n",
        "         DRUG,\n",
        "         DRUG_CLASS,\n",
        "         DECODED) |>\n",
        "  # counting total bugs-drug combinations\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           DRUG) |>\n",
        "  mutate(totalcombinations=n()) |>\n",
        "  ungroup() |>\n",
        "  # creating non-susceptible column\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           DRUG) |>\n",
        "  summarise(DECODED,\n",
        "            totalcombinations,\n",
        "            resistant = sum(DECODED == \"Resistant\" |\n",
        "                            DECODED == \"Intermediate\", na.rm = TRUE)) |>\n",
        "  distinct() |>\n",
        "  mutate(nonsusceptible=(resistant/totalcombinations)) |>\n",
        "  ungroup() |>\n",
        "  # selecting data bug-drug combinations > 5\n",
        "  filter(totalcombinations>5) |>\n",
        "  ungroup() |>\n",
        "  select(ORGANISM_OR_BUG,\n",
        "         DRUG,\n",
        "         nonsusceptible) |>\n",
        "  distinct() |>  \n",
        "  # left joining with drug classes\n",
        "  left_join(\n",
        "       #micro_cf_ALL |>\n",
        "       micro_cf_BLOOD |>\n",
        "            select(DRUG,\n",
        "                   DRUG_CLASS) |>\n",
        "            distinct(),\n",
        "            by = \"DRUG\") |>\n",
        "  # removing capitalisation of drug names\n",
        "  mutate(DRUG = str_to_title(DRUG)) |>\n",
        "  # plotting\n",
        "  ggplot(aes(x=DRUG,\n",
        "             y=nonsusceptible,\n",
        "             fill=DRUG_CLASS)) +\n",
        "  geom_col(alpha=0.8) +\n",
        "  labs(x = \"Drug\",\n",
        "       y = \"Resistance (%)\",\n",
        "       fill = \"Drug Class\",\n",
        "       size = \"Monthly Count\") +\n",
        "  theme_bw() +\n",
        "  theme(\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11, face = \"italic\"),\n",
        "          strip.background = element_blank(),\n",
        "          axis.title.x = element_text(vjust=2),\n",
        "        axis.text.x = element_text(angle=45,hjust=1)) +\n",
        "  scale_y_continuous(labels=scales::percent_format(scale=100)) +\n",
        "  #facet_wrap(~ORGANISM_OR_BUG) +\n",
        "  scale_fill_aaas() +\n",
        "  scale_size_binned(breaks = breaks,\n",
        "                    range = c(0.5, 4)) +\n",
        "  guides(fill = guide_legend(order = 1)) +\n",
        "  # first national lockdown date\n",
        "  geom_hline(yintercept=0.1,\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) +\n",
        "  scale_x_discrete(limit = c(\n",
        "       \"Amikacin\",\n",
        "       \"Gentamicin\",\n",
        "       \"Ertapenem\",\n",
        "       \"Meropenem\",\n",
        "       \"Ceftazidime\",\n",
        "       \"Ceftriaxone\",\n",
        "       \"Ciprofloxacin\",\n",
        "       \"Amoxycillin\",\n",
        "       \"Co-Amoxiclav\",\n",
        "       \"Tazocin\",\n",
        "       \"Temocillin\",\n",
        "       \"Cotrimoxazole\"\n",
        "  )) +\n",
        "  scale_fill_manual(values = c(\n",
        "       \"Aminoglycosides\"=\"#3B4992CC\",\n",
        "       \"Carbapenems\"=\"#EE0000CC\",\n",
        "       \"Cephalosporins\"=\"#008B45CC\",\n",
        "       \"Fluoroquinolones\"=\"#631879CC\",\n",
        "       \"Penicillins\"=\"#5F559BCC\",\n",
        "       \"Sulfonamides\"=\"#A20056CC\"\n",
        "  ))\n",
        "\n",
        "png(\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       width=5.33,\n",
        "       height=3,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## 11. bar chart (Kpn blood isolates, April 2020 - December 2021, HO vs CO)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751266629315
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# bar chart\n",
        "bld_data |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG == \"Klebsiella pneumoniae\") |>\n",
        "  # filtering for drugs of interest (defined in 4. GLMM)\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # filtering for April 2020 - December 2021\n",
        "  filter(SAMPLE_COLLECTED_DT >= as.Date(\"2020-04-01\") & SAMPLE_COLLECTED_DT <= as.Date(\"2021-12-31\")) |>\n",
        "  mutate(\n",
        "         # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\n",
        "            # else\n",
        "            \"Undefined\"))) |>\n",
        "  # filtering for drugs of interest (defined in 4. GLMM)\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         ORGANISM_OR_BUG,\n",
        "         DRUG,\n",
        "         HO,\n",
        "         DECODED) |>\n",
        "  # counting total bugs-drug combinations\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           DRUG,\n",
        "           HO) |>\n",
        "  mutate(totalcombinations=n()) |>\n",
        "  ungroup() |>\n",
        "  # creating non-susceptible column\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           DRUG,\n",
        "           HO) |>\n",
        "  summarise(DECODED,\n",
        "            totalcombinations,\n",
        "            resistant = sum(DECODED == \"Resistant\" |\n",
        "                            DECODED == \"Intermediate\", na.rm = TRUE)) |>\n",
        "  distinct() |>\n",
        "  mutate(nonsusceptible=(resistant/totalcombinations)) |>\n",
        "  ungroup() |>\n",
        "  # selecting data bug-drug combinations > 5\n",
        "  filter(totalcombinations>5) |>\n",
        "  ungroup() |>\n",
        "  select(ORGANISM_OR_BUG,\n",
        "         DRUG,\n",
        "         HO,\n",
        "         nonsusceptible) |>\n",
        "  distinct() |>\n",
        "  # removing capitalisation of drug names\n",
        "  mutate(DRUG = str_to_title(DRUG)) |>\n",
        "  # plotting\n",
        "  ggplot(aes(x=DRUG,\n",
        "             y=nonsusceptible,\n",
        "             fill=HO)) +\n",
        "  geom_col(alpha=0.8, position = \"dodge\") +\n",
        "  labs(x = \"Drug\",\n",
        "       y = \"Resistance (%)\",\n",
        "       fill = \"Infection Category\",\n",
        "       size = \"Monthly Count\") +\n",
        "  theme_bw() +\n",
        "  theme(\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11, face = \"italic\"),\n",
        "          strip.background = element_blank(),\n",
        "          axis.title.x = element_text(vjust=2),\n",
        "        axis.text.x = element_text(angle=45,hjust=1)) +\n",
        "  scale_y_continuous(labels=scales::percent_format(scale=100)) +\n",
        "  #facet_wrap(~ORGANISM_OR_BUG) +\n",
        "  scale_fill_aaas() +\n",
        "  scale_size_binned(breaks = breaks,\n",
        "                    range = c(0.5, 4)) +\n",
        "  guides(fill = guide_legend(order = 1)) +\n",
        "  # first national lockdown date\n",
        "  geom_hline(yintercept=0.1,\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) +\n",
        "  scale_x_discrete(limit = c(\n",
        "       \"Amikacin\",\n",
        "       \"Gentamicin\",\n",
        "       \"Ertapenem\",\n",
        "       \"Meropenem\",\n",
        "       \"Ceftazidime\",\n",
        "       \"Ceftriaxone\",\n",
        "       \"Ciprofloxacin\",\n",
        "       \"Amoxycillin\",\n",
        "       \"Co-Amoxiclav\",\n",
        "       \"Tazocin\",\n",
        "       \"Temocillin\",\n",
        "       \"Cotrimoxazole\"\n",
        "  )) +\n",
        "  scale_fill_npg()\n",
        "\n",
        "png(\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       width=6,\n",
        "       height=3,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# **<<< 4. TIME SERIES MODELLING >>>**"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# determining which drugs to choose for analyses\n",
        "\n",
        "## checking coverage of bug-drug combinations"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747134037873
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "#micro_cf_ALL |>\n",
        "#all_data |>\n",
        "#micro_cf_BLOOD |>\n",
        "bld_data |>\n",
        "  # filtering for bugs of interest\n",
        "  filter(ORGANISM_OR_BUG==\"Escherichia coli\" |\n",
        "           ORGANISM_OR_BUG==\"Klebsiella pneumoniae\") |>\n",
        "  # filtering for drugs of interest\n",
        "  filter(DRUG_CLASS != \"Other\") |>\n",
        "  count(DRUG,ORGANISM_OR_BUG) |>\n",
        "  spread(ORGANISM_OR_BUG,n) |>\n",
        "  arrange(desc(`Klebsiella pneumoniae`),desc(`Escherichia coli`))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "### aminoglycosides: gentamicin (excellent coverage), amikacin  (excellent coverage)\n",
        "### carbapenems: meropenem  (excellent coverage), ertapenem  (excellent coverage), imipenem (poor coverage - **REMOVED 17/04/2025**)\n",
        "### ESBL: cefotaxime (ok coverage, **REMOVED 28/04/2025**), ceftriaxone (excellent coverage), ceftazidime (excellent coverage), cefepime (poor coverage - **REMOVED 17/04/2025**), amoxycillin (excellent coverage - **ADDED 17/04/2025**), co-amoxiclav (excellent coverage - **ADDED 17/04/2025** )\n",
        "### potential CPE: tazocin (piperacillin-tazobactam) (excellent coverage), temocillin (excellent coverage), ciprofloxacin (excellent coverage), cotrimoxazole (trimethoprim-sulfamethoxazole) (ok coverage)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1745927183413
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# creating filtering vector for drugs clinically relevant in Kpn bacteraemia\n",
        "drugs_of_interest <- c(\"GENTAMICIN\",\"AMIKACIN\",\n",
        "                       \"MEROPENEM\",\"ERTAPENEM\",\n",
        "                       \"CEFTRIAXONE\",\"CEFTAZIDIME\", \"AMOXYCILLIN\",\"CO-AMOXICLAV\",\n",
        "                       \"TAZOCIN\",\"TEMOCILLIN\",\"CIPROFLOXACIN\",\"COTRIMOXAZOLE\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# exploring changes pre- and post-national lockdowns for interrupted analysis\n",
        "\n",
        "## model data: micro_cf_ALL or micro_cf_BLOOD as these are the most complete microbiology susceptibility testing data sets\n",
        "\n",
        "## use of scaled predictors:\n",
        "\n",
        "### helps convergence of glmer() and other mixed models\n",
        "### makes interaction terms (e.g., time:tp1) more stable\n",
        "### lets us interpret coefficients in terms of SD units, not raw time units, e.g., for each SD of time, log-odds increase/decrease by coefficient value"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1748529188291
        },
        "jupyter": {
          "outputs_hidden": false
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "model_data <-\n",
        "#micro_cf_ALL |>\n",
        "micro_cf_BLOOD |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # grouping other Enterobacteriaceae in \"Other\" category\n",
        "  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c(\"Escherichia coli\",\"Klebsiella pneumoniae\"), \n",
        "         ORGANISM_OR_BUG, \"Other Enterobacteriaceae\")) |>\n",
        "  # filtering for drugs of interest\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # creating month column\n",
        "  mutate(month=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\")) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(month < end_date) |>\n",
        "  # counting total bugs-drug combinations per month\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           month,\n",
        "           DRUG) |>\n",
        "  # creating total monthly count column\n",
        "  mutate(monthly_total=n()) |>\n",
        "  # selecting data for months with bug-drug combinations > 5\n",
        "  filter(monthly_total > 5) |>\n",
        "  # creating non-susceptible column\n",
        "  summarise(DECODED,\n",
        "            monthly_total,\n",
        "            monthly_resistant = sum(DECODED == \"Resistant\" |\n",
        "                                    DECODED == \"Intermediate\", na.rm = TRUE)) |>\n",
        "  ungroup() |>\n",
        "  # creating nonsusceptible column\n",
        "  mutate(nonsusceptible=(monthly_resistant/monthly_total)*100) |>\n",
        "  # arranging by month\n",
        "  arrange(month) |>\n",
        "  # creating model terms\n",
        "  mutate(time = as.numeric(difftime(month, min(month),max(month),unit = \"days\")) / 30.44, # average days per month\n",
        "         # rounding\n",
        "         time = round(time,1),\n",
        "         # lockdown 1 date\n",
        "         ld1 = as.Date(\"2020-03-23\"),\n",
        "         # lockdown 2 date\n",
        "         ld2 = as.Date(\"2020-11-05\"),\n",
        "         # lockdown 3 date\n",
        "         ld3 = as.Date(\"2021-01-06\"),\n",
        "         # time post lockdown 1\n",
        "         tp1 = if_else(month >= ld1, time - as.numeric(difftime(ld1, min(month), unit = \"days\")) / 30.44, 0), # converting time to months since lockdown 1\n",
        "         # time post lockdown 2\n",
        "         tp2 = if_else(month >= ld2, time - as.numeric(difftime(ld2, min(month), unit = \"days\")) / 30.44, 0),\n",
        "         # time post lockdown 3\n",
        "         tp3 = if_else(month >= ld3, time - as.numeric(difftime(ld3, min(month), unit = \"days\")) / 30.44, 0)) |>\n",
        "  # rescaling predictors\n",
        "  mutate(across(c(time, tp1, tp2, tp3), scale)) |>\n",
        "  distinct()\n",
        "# viewing model data\n",
        "kable(model_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## **<<< SAVING MODEL DATA FOR FURTHER WORK (OFF ICARE) >>>**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1748529203085
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# model_data_micro_cf_ALL - DONE\n",
        "# model_data_micro_cf_BLOOD - DONE\n",
        "#write_xlsx(model_data, \"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/model_data_micro_cf_BLOOD_29052025.xlsx\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# **glmer()**\n",
        "## **working model**: glmer(cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * (tp1 + tp2 + tp3) + (1|ORGANISM_OR_BUG:DRUG))\n",
        "\n",
        "## **cbind(monthly_resistant, monthly_total - monthly_resistant)**: for each bug:drug combination in a given month, there is a number of resistant isolates out of a total number of isolates tested; we are modelling the probability of resistance in binomial framework\n",
        "## **time**: baseline trend - in log odds - of resistance over time, before lockdown 1\n",
        "## **tpX**: immediate step change - in log odds - of resistance at lockdown X\n",
        "## **time:tpX**: change in trend after lockdown X; e.g., did the slope of the time trend change after lockdown X?\n",
        "## **(1|ORGANISM_OR_BUG:DRUG)**: random intercept for each bug-drug combination; accounts for baseline differences in resistance levels across different bug:drug combinations\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "### model"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747134060451
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "interrupted_ts <- glmer(cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * (tp1 + tp2 + tp3) + (1|ORGANISM_OR_BUG:DRUG),\n",
        "                        data = model_data, \n",
        "                        family = \"binomial\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## model selection\n",
        "\n",
        "### avoiding rules to prevent biasing model selection"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747134112868
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "options(na.action = \"na.fail\")\n",
        "\n",
        "model_set <- dredge(interrupted_ts)\n",
        "\n",
        "kable(model_set)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## testing model assumptions"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747134160959
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# qqplot of random intercepts\n",
        "## straight line = perfectly normal\n",
        "## plots shows approximate normality of random effects (deviation at tails)\n",
        "lattice::qqmath(ranef(interrupted_ts, condVar = TRUE))\n",
        "## plot not showing here for some reason - looked ok at last check\n",
        "\n",
        "# heteroscedasticity\n",
        "## residuals show varying spread across different fitted values\n",
        "plot(interrupted_ts)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## model summary"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747134168337
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "summary(get.models(model_set, 1)[[1]])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## **intercept:** baseline log odds at time 0, before lockdown 1\n",
        "## **time:** baseline trend in log odds\n",
        "## **tp1:** immediate step change at lockdown 1\n",
        "## **tp2:** immediate step change at lockdown 2\n",
        "## **tp3:** immediate step change at lockdown 3\n",
        "## **time:tp1:** change in trend post lockdown 1\n",
        "## **time:tp2:** change in trend post lockdown 2\n",
        "## **time:tp3:** change in trend post lockdown 3"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# **glm()**\n",
        "\n",
        "# looking at bug:drug combinations separately\n",
        "\n",
        "## testing for normality across bug-drug combinations"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747134631823
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "model_data_test <- model_data |>\n",
        "    group_by(DRUG, ORGANISM_OR_BUG) |>\n",
        "    summarise(\n",
        "        n = n(),\n",
        "        p = if_else(n>=3,shapiro.test(nonsusceptible)$p.value, NA_real_)\n",
        "    )\n",
        "\n",
        "# non-normal if p < 0.05\n",
        "kable(model_data_test |>\n",
        "        filter(p > 0.05))\n",
        "## therefore, 4/24 normal"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## plotting for normality across bug-drug combinations"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747134570837
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "ggplot(model_data,\n",
        "    aes(x=nonsusceptible)) +\n",
        "    geom_histogram() +\n",
        "    facet_wrap(~ interaction(DRUG,ORGANISM_OR_BUG), scales = \"free_y\")\n",
        "\n",
        "ggsave(plot=last_plot(),\n",
        "       \"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       height= 10,\n",
        "       width=20)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## **working model across both micro_cf_ALL and micro_cf_BLOOD**: glm(cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * tp1\n",
        "### including tp1, tp2, & tp3 at bug:drug level, we risk overfitting, colinearity, and a lack of statistical power to detect changes here\n",
        "### lockdowns 1, 2, & 3 were relatively close together in time, when in the context of the wider data set (~10 years), therefore, including only lockdown 1 (time post lockdown 1; tp1) appears a statistically cleaner choice\n",
        "### the first lockdown likely corresponds to the biggest health disruption, the strongest public health response, and the most important change in behaviour"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747045780586
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# splitting by  bug-drug combination\n",
        "models <- model_data |>\n",
        "    ungroup() |>\n",
        "    group_by(DRUG, ORGANISM_OR_BUG) |>\n",
        "    group_split()\n",
        "\n",
        "# generating model names list\n",
        "model_names <- map_chr(models, ~ paste0(str_to_title(.x$DRUG[1]), \": \", str_to_title(.x$ORGANISM_OR_BUG[1])))\n",
        "\n",
        "# naming the models\n",
        "named_models <- set_names(models, model_names)\n",
        "\n",
        "# fitting models and computing acf\n",
        "fitted_models <-\n",
        "    map(named_models, ~glm(\n",
        "        cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * tp1,\n",
        "        data = .x,\n",
        "        family = \"binomial\"\n",
        "    ))\n",
        "\n",
        "# model summaries\n",
        "model_summaries <- map_dfr(fitted_models, ~ tidy(.x) |>\n",
        "                           mutate(aic = AIC(.x),\n",
        "                                  deviance = deviance(.x),\n",
        "                                  n_obs = nobs(.x)), .id = \"Drug: Bug\")\n",
        "\n",
        "# acf summaries\n",
        "acf_summary <- map_dfr(fitted_models, function(model) {\n",
        "     resids <- resid(model, type = \"pearson\")\n",
        "     acf_vals <- acf(resids, lag.max=3, plot=FALSE)$acf\n",
        "     \n",
        "     tibble(\n",
        "            lag1_auto = acf_vals[2],\n",
        "            lag2_auto = acf_vals[3],\n",
        "            lag3_auto = acf_vals[4],\n",
        "        )\n",
        "\n",
        "}, .id = \"Drug: Bug\")\n",
        "\n",
        "all_summaries <- left_join(model_summaries, acf_summary, by = \"Drug: Bug\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## viewing summaries data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747045790056
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "kable(all_summaries)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## as we can see from the lag1_auto column, month-to-month dependence is non-negligible\n",
        "## therefore, we ought to account for this autocorrelation by creating a lagged predictor that represents the previous months resistance"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747134749419
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# splitting by  bug-drug combination\n",
        "models <- model_data |>\n",
        "    ungroup() |>\n",
        "    group_by(DRUG, ORGANISM_OR_BUG) |>\n",
        "    # ensuring time ordering within each group\n",
        "    arrange(time, .by_group = TRUE) |>\n",
        "    # adding lagged predictor\n",
        "    mutate(lag1_resistance = lag(monthly_resistant / monthly_total, n=1)) |>\n",
        "    group_split()\n",
        "\n",
        "# generating model names list\n",
        "model_names <- map_chr(models, ~ paste0(str_to_title(.x$DRUG[1]), \": \", str_to_title(.x$ORGANISM_OR_BUG[1])))\n",
        "\n",
        "# naming the models\n",
        "named_models <- set_names(models, model_names)\n",
        "\n",
        "# fitting models and computing acf\n",
        "fitted_models <-\n",
        "    map(named_models, ~glm(\n",
        "        cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * tp1 + lag1_resistance,\n",
        "        # removing NA lagged values which will hinder model fit\n",
        "        data = drop_na(.x, lag1_resistance),\n",
        "        family = \"binomial\"\n",
        "    ))\n",
        "\n",
        "# model summaries\n",
        "model_summaries <- map_dfr(fitted_models, ~ tidy(.x) |>\n",
        "                           mutate(aic = AIC(.x),\n",
        "                                  deviance = deviance(.x),\n",
        "                                  n_obs = nobs(.x)), .id = \"Drug: Bug\")\n",
        "\n",
        "# acf summaries\n",
        "acf_summary <- map_dfr(fitted_models, function(model) {\n",
        "     resids <- resid(model, type = \"pearson\")\n",
        "     acf_vals <- acf(resids, lag.max=3, plot=FALSE)$acf\n",
        "     \n",
        "     tibble(\n",
        "            lag1_auto = acf_vals[2],\n",
        "            lag2_auto = acf_vals[3],\n",
        "            lag3_auto = acf_vals[4],\n",
        "        )\n",
        "\n",
        "}, .id = \"Drug: Bug\")\n",
        "\n",
        "all_summaries <- left_join(model_summaries, acf_summary, by = \"Drug: Bug\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## viewing summaries data\n",
        "### AIC and deviance drop dramatically, indicating better model fit\n",
        "### lag1_auto correlation decreases\n",
        "### lag1_resistance term significant, supporting its explanatory power\n",
        "### therefore, overall, model better captures momentum/inertia"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747045800030
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "kable(all_summaries)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## plotting model summaries\n",
        "\n",
        "### 12. model terms plot version 1"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747046170774
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "model_summaries |>\n",
        "    # selecting model terms of interest\n",
        "    filter(\n",
        "    term != \"(Intercept)\" &\n",
        "    term != \"lag1_resistance\"\n",
        "    #\"time\"\n",
        "    #\"tp1\"\n",
        "    #\"time:tp1\"\n",
        "    ) |>\n",
        "    # filtering for significance\n",
        "    #filter(p.value < 0.05) |>\n",
        "    # converting to OR\n",
        "    mutate(OR = exp(estimate),\n",
        "           OR_low = exp(estimate - 1.96 * std.error),\n",
        "           OR_high = exp(estimate + 1.96 * std.error),\n",
        "           sign = if_else(OR < 1, \"-ve\", \"+ve\"),\n",
        "           # reordering factor levels\n",
        "           term = factor(term, levels = c(\"time\",\"tp1\",\"time:tp1\")),\n",
        "           # recoding factors\n",
        "           term = recode(term, \n",
        "                         \"time\"=\"Baseline Trend\",\n",
        "                         \"tp1\"=\"Immediate Step Change\\nAt Intervention\",\n",
        "                         \"time:tp1\"=\"Change In Baseline Trend\\nFollowing Intervention\")) |>\n",
        "       # separating Drug: Bug column\n",
        "       separate(`Drug: Bug`, into =c(\"Drug\",\"Bug\"), sep = \":\\\\s*\")  |>\n",
        "    # making second word in Bug column lower case\n",
        "    mutate(Bug = str_split_fixed(Bug, \" \", 2)) |>\n",
        "    mutate(Bug = paste0(Bug[,1], \" \", str_to_lower(Bug[,2]))) |>\n",
        "    # filtering for finite and non-negative values\n",
        "    filter(is.finite(OR) &\n",
        "            OR > 0) |>\n",
        "    # plotting\n",
        "    ggplot(aes(\n",
        "               x=Drug,\n",
        "               y=OR,\n",
        "               colour=Bug\n",
        "               )) +\n",
        "    # enabling log and linear scales simultaneously\n",
        "    scale_y_log10(breaks = c(0,0.1,0.2,0.5,1,2,5,10\n",
        "                 ),\n",
        "                  labels = label_number()) +\n",
        "    geom_point(size = 1, position = position_dodge(width=0.5)) +\n",
        "    geom_errorbar(aes(ymin = OR_low,\n",
        "                      ymax = OR_high),\n",
        "                  alpha = 0.5,\n",
        "                  width = 0.4,\n",
        "                  position = position_dodge(width=0.5)) +\n",
        "    theme_bw() +\n",
        "    # comment out to view mega extremes\n",
        "    labs(x=\"\",\n",
        "         colour=\"Organism\",\n",
        "         y=\"Odds Ratio (Log Scale)\") +\n",
        "    geom_hline(yintercept = 1, linetype = \"dashed\",colour=\"grey\") +\n",
        "    scale_colour_manual(values = c(\"#008080\",\"#FFA500\")) +\n",
        "    theme(axis.title.x = element_blank(),\n",
        "          axis.title.y = element_text(vjust = 2),\n",
        "          axis.text.x = element_text(angle=45,hjust=1),\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11),\n",
        "          strip.background = element_blank(),\n",
        "          # margin\n",
        "          plot.margin = margin(1,1,1,40, unit = \"pt\")) +\n",
        "    facet_wrap(~term)\n",
        "\n",
        "ggsave(plot=last_plot(),\n",
        "       \"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/12_micro_cf_ALL_OR_model_terms.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/12_micro_cf_BLOOD_OR_model_terms.jpeg\",\n",
        "       height= 5,\n",
        "       width=14)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "### 12. model terms plot version 2"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747045903682
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "model_summaries |>\n",
        "    # selecting model terms of interest\n",
        "    filter(\n",
        "    term != \"(Intercept)\" &\n",
        "    term != \"lag1_resistance\"\n",
        "    #\"time\"\n",
        "    #\"tp1\"\n",
        "    #\"time:tp1\"\n",
        "    ) |>\n",
        "    # filtering for significance\n",
        "    #filter(p.value < 0.05) |>\n",
        "    # converting to OR\n",
        "    mutate(OR = exp(estimate),\n",
        "           OR_low = exp(estimate - 1.96 * std.error),\n",
        "           OR_high = exp(estimate + 1.96 * std.error),\n",
        "           sign = if_else(OR < 1, \"-ve\", \"+ve\"),\n",
        "           # reordering factor levels\n",
        "           term = factor(term, levels = c(\"time\",\"tp1\",\"time:tp1\")),\n",
        "           # recoding factors\n",
        "           term = recode(term, \n",
        "                         \"time\"=\"Baseline Trend\",\n",
        "                         \"tp1\"=\"Immediate Step Change\\nAt Intervention\",\n",
        "                         \"time:tp1\"=\"Change In Baseline Trend\\nFollowing Intervention\")) |>\n",
        "       # separating Drug: Bug column\n",
        "       separate(`Drug: Bug`, into =c(\"Drug\",\"Bug\"), sep = \":\\\\s*\") |>\n",
        "    # making second word in Bug column lower case\n",
        "    mutate(Bug = str_split_fixed(Bug, \" \", 2)) |>\n",
        "    mutate(Bug = paste0(Bug[,1], \" \", str_to_lower(Bug[,2]))) |>\n",
        "    # filtering for finite and non-negative values\n",
        "    filter(is.finite(OR) &\n",
        "            OR > 0) |>\n",
        "    # plotting\n",
        "    ggplot(aes(\n",
        "               x=term,\n",
        "               y=OR,\n",
        "               group=Drug,\n",
        "               colour=Drug\n",
        "               )) +\n",
        "    # enabling log and linear scales simultaneously\n",
        "    scale_y_log10(breaks = c(0.0,0.1,0.2,0.5,1,2,5,10\n",
        "                 ),\n",
        "                  labels = label_number()) +\n",
        "    geom_point(size = 1,position = position_dodge(width=0.5)) +\n",
        "    #geom_line(linewidth = 0.3, alpha = 0.8, position = position_dodge(width=0.5)) +\n",
        "    geom_errorbar(aes(ymin = OR_low,\n",
        "                      ymax = OR_high),\n",
        "                  alpha = 0.5,\n",
        "                  width = 0.4,\n",
        "                  position = position_dodge(width=0.5)) +\n",
        "    theme_bw() +\n",
        "    labs(x=\"\",\n",
        "         colour=\"Drug\",\n",
        "         y=\"Odds Ratio (Log Scale)\") +\n",
        "    geom_hline(yintercept = 1, linetype = \"dashed\",colour=\"grey\") +\n",
        "    scale_colour_igv() +\n",
        "    theme(axis.title.x = element_blank(),\n",
        "          axis.title.y = element_text(vjust = 2),\n",
        "          axis.text.x = element_text(angle=45,hjust=1),\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11),\n",
        "          strip.background = element_blank(),\n",
        "          # margin\n",
        "          plot.margin = margin(1,1,1,40, unit = \"pt\")) +\n",
        "    facet_wrap(~Bug)\n",
        "\n",
        "ggsave(plot=last_plot(),\n",
        "       \"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/12_micro_cf_ALL_OR_model_terms_v2.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/12_micro_cf_BLOOD_OR_model_terms_v2.jpeg\",\n",
        "       height= 7,\n",
        "       width=14)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## **Log Odds**\n",
        "### **Log Odds ~0**: No effect\n",
        "### **Log Odds > 0 **: Increase in probability (positive effect; e.g., odds double at log odds = 0.7 since exp(0.7)=2)\n",
        "### **Log Odds < 0 **: Decrease in probability (negative effect; e.g., odds halve at log odds = -0.7 since exp(-0.7)=0.5)\n",
        "\n",
        "## **Use exp(Log Odds) to generate Odds Ratio (OR)**\n",
        "### **OR ~1.0**: No real effect\n",
        "### **OR > 1**: Odds increased\n",
        "### **OR < 1**: Odds decreased\n",
        "### **OR > 1.2 or OR < 0.8**: small but real effect\n",
        "### **OR > 2 or OR < 0.5**: large effect\n",
        "\n",
        "## **Confidence Intervals**\n",
        "### **95% CI overlapping 1**: Not statistically significant\n",
        "### **Wide CI**: Low certainty, likely due to a small n\n",
        "\n",
        "## hence\n",
        "### 1. for most bug:drug combinations, resistance was increasing over time (+ve slope), before intervention\n",
        "### 2. for most bug:drug combinations, there was an immediate step decrease in resistance following intervention (tp1)\n",
        "### 3. for most bug:drug combinations, there was a subsequent increase in resistance slope post intervention (time:tp1)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# exploring differences in trends across CO vs HO infections\n",
        "\n",
        "## model data: all_data or bld_data as microbiology have been matched to patient data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1748529606143
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "model_data <-\n",
        "#all_data |>\n",
        "bld_data |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # grouping other Enterobacteriaceae in \"Other\" category\n",
        "  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c(\"Escherichia coli\",\"Klebsiella pneumoniae\"), \n",
        "         ORGANISM_OR_BUG, \"Other Enterobacteriaceae\")) |>\n",
        "  # filtering for drugs of interest\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # creating month column\n",
        "  mutate(month=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\"),\n",
        "         # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\n",
        "            # else\n",
        "            \"Undefined\"))) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(month < end_date) |>\n",
        "  # counting total bugs-drug combinations per month\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           HO,\n",
        "           month,\n",
        "           DRUG) |>\n",
        "  # creating total monthly count column\n",
        "  mutate(monthly_total=n()) |>\n",
        "  # selecting data for months with bug-drug combinations > 5\n",
        "  filter(monthly_total > 5) |>\n",
        "  # creating non-susceptible column\n",
        "  summarise(DECODED,\n",
        "            monthly_total,\n",
        "            monthly_resistant = sum(DECODED == \"Resistant\" |\n",
        "                                    DECODED == \"Intermediate\", na.rm = TRUE)) |>\n",
        "  ungroup() |>\n",
        "  # creating nonsusceptible column\n",
        "  mutate(nonsusceptible=(monthly_resistant/monthly_total)*100) |>\n",
        "  # arranging by month\n",
        "  arrange(month) |>\n",
        "  # creating model terms\n",
        "  mutate(time = as.numeric(difftime(month, min(month),max(month),unit = \"days\")) / 30.44, # average days per month\n",
        "         # rounding\n",
        "         time = round(time,1),\n",
        "         # lockdown 1 date\n",
        "         ld1 = as.Date(\"2020-03-23\"),\n",
        "         # lockdown 2 date\n",
        "         ld2 = as.Date(\"2020-11-05\"),\n",
        "         # lockdown 3 date\n",
        "         ld3 = as.Date(\"2021-01-06\"),\n",
        "         # time post lockdown 1\n",
        "         tp1 = if_else(month >= ld1, time - as.numeric(difftime(ld1, min(month), unit = \"days\")) / 30.44, 0), # converting time to months since lockdown 1\n",
        "         # time post lockdown 2\n",
        "         tp2 = if_else(month >= ld2, time - as.numeric(difftime(ld2, min(month), unit = \"days\")) / 30.44, 0),\n",
        "         # time post lockdown 3\n",
        "         tp3 = if_else(month >= ld3, time - as.numeric(difftime(ld3, min(month), unit = \"days\")) / 30.44, 0),\n",
        "         # onset term\n",
        "         HO = relevel(factor(HO), ref = \"Community Onset\")\n",
        "         ) |>\n",
        "  # rescaling predictors\n",
        "  mutate(across(c(time, tp1, tp2, tp3), scale)) |>\n",
        "  distinct()\n",
        "# viewing model data\n",
        "kable(model_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## **<<< SAVING MODEL DATA FOR FURTHER WORK (OFF ICARE) >>>**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1748529620522
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# model_data_all_data - DONE\n",
        "# model_data_bld_data - DONE\n",
        "#write_xlsx(model_data, \"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/model_data_bld_data_29052025.xlsx\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## model selection"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1745937628141
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# working model\n",
        "interrupted_ts_onsetterm <- glmer(cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * tp1 * HO + (1|ORGANISM_OR_BUG:DRUG),\n",
        "                                        data = model_data, \n",
        "                                        family = \"binomial\")\n",
        "\n",
        "                        options(na.action = \"na.fail\")\n",
        "\n",
        "# model selection\n",
        "model_set <- dredge(interrupted_ts_onsetterm)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## model summary"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1745937131050
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "summary(get.models(model_set, 1)[[1]])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## **intercept:** baseline log odds at time 0, before lockdown 1, for CO reference group\n",
        "## **time:** baseline trend in resistance, before lockdown 1, for CO reference group\n",
        "## **tp1:** immediate step change at lockdown 1 for CO reference group\n",
        "## **HOHospital Onset:** difference in baseline log odds at time 0, before lockdown 1, between HO group and CO reference group\n",
        "## **HOHospital Onset:time:** difference in trend in resistance, before lockdown 1, between HO group and CO reference group\n",
        "## **HOHospital Onset:tp1:** difference in immediate step change at lockdown 1 between HO group and CO reference group\n",
        "## **time:tp1:** change in trend post lockdown 1 (compared to baseline) for CO reference group\n",
        "## **HOHospital Onset:time:tp1:** difference in change in trend post lockdown 1 between HO group and CO reference group"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## **model inferences**\n",
        "## **all_data**\n",
        "### **intercept:** exp(-0.49) = 0.61 = the odds of resistance at baseline for CO infections\n",
        "### **time:** resistance was increasing over time for CO infections\n",
        "### **tp1:** drop in resistance for CO infections following lockdown 1\n",
        "### **HOHospital Onset:** exp(0.46) = 1.58 = 58% higher odds of resistance at baseline for HO infectiosn\n",
        "### **HOHospital Onset:time:** resistance was increasing more slowly over time for HO infections\n",
        "### **HOHospital Onset:tp1:** drop in resistance was smaller for HO infections following lockdown 1\n",
        "### **time:tp1:** trend increased more steeply post lockdown 1 (compared to baseline) for CO infections\n",
        "### **HOHospital Onset:time:tp1:** trends increased even more steeply post lockdown 1 for HO infections\n",
        "\n",
        "## **bld_data**\n",
        "### **intercept:** exp(-0.76) = 0.47 = the odds of resistance at baseline for CO infections\n",
        "### **time:** resistance was increasing over time for CO infections\n",
        "### **tp1:** drop in resistance for CO infections following lockdown 1\n",
        "### **HOHospital Onset:** exp(0.49) = 1.63 = 63% higher odds of resistance at baseline for HO infections\n",
        "### **HOHospital Onset:time:** resistance was increasing more slowly over time for HO infections\n",
        "### **HOHospital Onset:tp1:** drop in resistance was smaller for HO infections following lockdown 1\n",
        "### **time:tp1:** trend increased more steeply post lockdown 1 (compared to baseline) for CO infections\n",
        "### **HOHospital Onset:time:tp1:** trends increased even more steeply post lockdown 1 for HO infections\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## looking at bug:drug combinations and HO versus CO infections separately"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747137003969
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# splitting by  bug-drug combination\n",
        "models <- model_data |>\n",
        "    ungroup() |>\n",
        "    group_by(DRUG, ORGANISM_OR_BUG) |>\n",
        "    # ensuring time ordering within each group\n",
        "    arrange(time, .by_group = TRUE) |>\n",
        "    # adding lagged predictor\n",
        "    mutate(lag1_resistance = lag(monthly_resistant / monthly_total, n=1)) |>\n",
        "    group_split()\n",
        "\n",
        "# generating model names list\n",
        "model_names <- map_chr(models, ~ paste0(str_to_title(.x$DRUG[1]), \": \",\n",
        "                                        str_to_title(.x$ORGANISM_OR_BUG[1]), \": \",\n",
        "                                        str_to_title(.x$HO[1])))\n",
        "\n",
        "# naming the models\n",
        "named_models <- set_names(models, model_names)\n",
        "\n",
        "# fitting models and computing acf\n",
        "fitted_models <-\n",
        "    map(named_models, ~glm(\n",
        "        cbind(monthly_resistant, monthly_total - monthly_resistant) ~ time * tp1 * HO + lag1_resistance,\n",
        "        # removing NA lagged values which will hinder model fit\n",
        "        data = drop_na(.x, lag1_resistance),\n",
        "        family = \"binomial\"\n",
        "    ))\n",
        "\n",
        "# model summaries\n",
        "model_summaries <- map_dfr(fitted_models, ~ tidy(.x) |>\n",
        "                           mutate(aic = AIC(.x),\n",
        "                                  deviance = deviance(.x),\n",
        "                                  n_obs = nobs(.x)), .id = \"Drug: Bug: Onset\")\n",
        "\n",
        "# acf summaries\n",
        "acf_summary <- map_dfr(fitted_models, function(model) {\n",
        "     resids <- resid(model, type = \"pearson\")\n",
        "     acf_vals <- acf(resids, lag.max=3, plot=FALSE)$acf\n",
        "     \n",
        "     tibble(\n",
        "            lag1_auto = acf_vals[2],\n",
        "            lag2_auto = acf_vals[3],\n",
        "            lag3_auto = acf_vals[4],\n",
        "        )\n",
        "\n",
        "}, .id = \"Drug: Bug: Onset\")\n",
        "\n",
        "all_summaries <- left_join(model_summaries, acf_summary, by = \"Drug: Bug: Onset\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## viewing summaries data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747137623941
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "kable(all_summaries)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## plotting model summaries\n",
        "\n",
        "### 13. model terms plot version 2"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1747137836430
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "all_summaries |>\n",
        "    # selecting model terms of interest\n",
        "    filter(term !=\"(Intercept)\" &\n",
        "           term != \"HOHospital Onset\" &\n",
        "           term !=\"lag1_resistance\"\n",
        "    #\"time\"\n",
        "    #\"tp1\"\n",
        "    #\"time:tp1\"\n",
        "    ) |>\n",
        "    # converting to OR\n",
        "    mutate(OR = exp(estimate),\n",
        "           OR_low = exp(estimate - 1.96 * std.error),\n",
        "           OR_high = exp(estimate + 1.96 * std.error),\n",
        "           sign = if_else(OR < 1, \"-ve\", \"+ve\"),\n",
        "           # reordering factor levels\n",
        "           term = factor(term, levels = c(\"time\",\"tp1\",\"time:tp1\",\"time:HOHospital Onset\",\"tp1:HOHospital Onset\",\"time:tp1:HOHospital Onset\")),\n",
        "           # recoding factors\n",
        "           term = recode(term, \n",
        "                         \"time\"=\"Baseline Trend\",\n",
        "                         \"tp1\"=\"Immediate Step Change\\nat Intervention\",\n",
        "                         \"time:tp1\"=\"Change in Baseline Trend\\nFollowing Intervention\",\n",
        "                         \"time:HOHospital Onset\"=\"Difference\\nin Baseline Trend\",\n",
        "                         \"tp1:HOHospital Onset\"=\"Difference in\\nImmediate Step Change\\nAt Intervention\",\n",
        "                         \"time:tp1:HOHospital Onset\"=\"Difference\\nin Change in Baseline\\nTrend Following Intervention\")) |>\n",
        "    # separating Drug: Bug column\n",
        "    separate(`Drug: Bug: Onset`, into =c(\"Drug\",\"Bug\",\"Onset\"), sep = \":\\\\s*\") |>\n",
        "    # making second word in Bug column lower case\n",
        "    mutate(Bug = str_split_fixed(Bug, \" \", 2)) |>\n",
        "    mutate(Bug = paste0(Bug[,1], \" \", str_to_lower(Bug[,2]))) |>\n",
        "    # filtering for finite and non-negative values\n",
        "    filter(is.finite(OR) &\n",
        "            OR > 0)\n",
        "    \n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# plotting\n",
        "    ggplot(aes(\n",
        "               x=term,\n",
        "               y=OR,\n",
        "               group=Drug,\n",
        "               colour=Drug\n",
        "               )) +\n",
        "    # enabling log and linear scales simultaneously\n",
        "    scale_y_log10(labels = label_number()) +\n",
        "    geom_point(size = 1,position = position_dodge(width=0.5)) +\n",
        "    #geom_line(linewidth = 0.3, alpha = 0.8, position = position_dodge(width=0.5)) +\n",
        "    geom_errorbar(aes(ymin = OR_low,\n",
        "                      ymax = OR_high),\n",
        "                  alpha = 0.5,\n",
        "                  width = 0.4,\n",
        "                  position = position_dodge(width=0.5)) +\n",
        "    theme_bw() +\n",
        "    labs(x=\"\",\n",
        "         colour=\"Drug\",\n",
        "         y=\"Odds Ratio (Log Scale)\") +\n",
        "    geom_hline(yintercept = 1, linetype = \"dashed\",colour=\"grey\") +\n",
        "    scale_colour_igv() +\n",
        "    theme(axis.title.x = element_blank(),\n",
        "          axis.title.y = element_text(vjust = 2),\n",
        "          axis.text.x = element_text(angle=45,hjust=1),\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11),\n",
        "          strip.background = element_blank(),\n",
        "          # margin\n",
        "          plot.margin = margin(1,1,1,40, unit = \"pt\")) +\n",
        "    facet_grid(~Bug)\n",
        "\n",
        "ggsave(plot=last_plot(),\n",
        "       \"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/13_all_data_HO_vs_CO_OR_model_terms_v2.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/13_bld_data_HO_vs_CO_OR_model_terms_v2.jpeg\",\n",
        "       height= 7,\n",
        "       width=14)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# **<<< 5. ARIMA >>>**\n",
        "# 1_time_series_modelling.Rmd"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# **<<< 6. COMPARISONS WITH NATIONAL DATA >>>**\n",
        "\n",
        "# loading national data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751120536250
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# espaur data\n",
        "espaur_data <- read.csv(\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/ESPAUR_data.csv\")\n",
        "head(espaur_data)\n",
        "\n",
        "# ukhsa data\n",
        "ukhsa_data <- read.csv(\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/data/UKHSA_Apr2020-Mar2022.csv\")\n",
        "head(ukhsa_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# joining espaur data with micro_cf_BLOOD data\n",
        "\n",
        "## tidying espaur data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751120542397
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "espaur_data <- \n",
        "    espaur_data |>\n",
        "    # selecting columns of interest as they relate to the micro_cf_BLOOD data\n",
        "    select(ORGANISM_OR_BUG=Bug, \n",
        "           DRUG_CLASS=Drug,\n",
        "           time=Year,\n",
        "           total_CLASS=total.isolates,\n",
        "           resistant_CLASS=total.resistant.isolates\n",
        "           ) |>\n",
        "    # reclassifying columns\n",
        "    mutate(ORGANISM_OR_BUG = as.factor(ORGANISM_OR_BUG),\n",
        "           DRUG_CLASS = as.factor(str_to_title(DRUG_CLASS)),\n",
        "           total_CLASS = as.integer(gsub(\",\", \"\", total_CLASS)),\n",
        "           resistant_CLASS = as.integer(gsub(\",\",\"\", resistant_CLASS))) |>\n",
        "    # changing pip-taz to TAZOCIN\n",
        "    mutate(DRUG_CLASS = str_replace(DRUG_CLASS,\"Piperacillin With Tazobactam\", \"Tazocin\")) |>\n",
        "    # reclassifying date column\n",
        "    mutate(time = as.Date(paste0(time,\"-01-01\"))) |>\n",
        "    # removing note annotations\n",
        "    mutate(DRUG_CLASS = str_remove(DRUG_CLASS, \" \\\\[Note \\\\d+\\\\]\")) |>\n",
        "    # reordering columns\n",
        "    relocate(time, .before = total_CLASS) |>\n",
        "    # creating column to differentiate data\n",
        "    mutate(dataset = \"ESPAUR 2024\")\n",
        "head(espaur_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## tidying micro_cf_BLOOD data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751120548421
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "to_bind <-\n",
        "micro_cf_BLOOD |>\n",
        "  # filtering for bugs of interest\n",
        "  filter(ORGANISM_OR_BUG==\"Escherichia coli\" |\n",
        "           ORGANISM_OR_BUG==\"Klebsiella pneumoniae\") |>\n",
        "  # filtering for drugs of interest (defined in 4. GLMM)\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # removing additional drugs not mentioned in ESPAUR\n",
        "  filter(!DRUG %in% c(\"AMOXYCILLIN\",\"COTRIMOXAZOLE\",\"TEMOCILLIN\")) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         ORGANISM_OR_BUG,\n",
        "         DRUG,\n",
        "         DECODED) |>\n",
        "  # creating time interval column\n",
        "  mutate(\n",
        "    # uncomment depending on time interval selection: name must match espaur data\n",
        "    time=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"year\"),\n",
        "    #time=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"quarter\"),\n",
        "    # reclassiyfing drugs per ESPAUR report\n",
        "    DRUG_CLASS = case_when(\n",
        "        # carbapenems\n",
        "        DRUG %in% c(\"ERTAPENEM\",\"IMIPENEM\",\"MEROPENEM\") ~ \"Carbapenems\",\n",
        "        # third generation cephalosporins\n",
        "        DRUG %in% c(\"CEFOTAXIME\", \"CEFTAZIDIME\", \"CEFPODOXIME\",\"CEFTRIAXONE\") ~ \"Third Generation Cephalosporins\",\n",
        "        TRUE ~ str_to_title(DRUG))\n",
        "        ) |>\n",
        "  # counting total bugs-drug combinations per time interval by drug\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           time,\n",
        "           DRUG) |>\n",
        "  # creating total count column\n",
        "  mutate(\n",
        "         total_DRUG=n()\n",
        "         ) |>\n",
        "  ungroup() |>\n",
        "  # counting total bugs-drug combinations per time interval by drug class (ESPAUR report)\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           time,\n",
        "           DRUG_CLASS) |>\n",
        "  # creating total timely count column\n",
        "  mutate(\n",
        "        total_CLASS=n()\n",
        "        ) |>\n",
        "  ungroup() |>\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           time,\n",
        "           DRUG_CLASS) |>\n",
        "  summarise(DECODED,\n",
        "            total_CLASS,\n",
        "            resistant_CLASS = sum(DECODED == \"Resistant\" |\n",
        "                                  DECODED == \"Intermediate\", na.rm = TRUE)) |>\n",
        "  select(-DECODED) |>\n",
        "  relocate(\n",
        "          time, .before = total_CLASS\n",
        "          ) |>\n",
        "  distinct() |>\n",
        "  # creating column to differentiate data\n",
        "  mutate(dataset = \"iCARE\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## visually checking data align"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751120552494
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "head(espaur_data)\n",
        "head(to_bind)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## binding both datasets"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751120557138
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "espaur_data <- rbind(espaur_data,to_bind)\n",
        "\n",
        "# creating nonsusceptible column\n",
        "espaur_data <- espaur_data |>\n",
        "        mutate(nonsusceptible=(resistant_CLASS/total_CLASS)*100) |>\n",
        "  # selecting data for years with bug-drug combinations > 5\n",
        "  filter(total_CLASS>5)\n",
        "\n",
        "kable(espaur_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting E. coli and K. pneumoniae yearly resistance rates selected drugs: micro_cf_BLOOD vs espaur data\n",
        "\n",
        "## 14. line chart"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751121081110
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "espaur_data |>\n",
        "  # reordering factors\n",
        "  mutate(dataset = factor(dataset, levels = c(\"iCARE\",\"ESPAUR 2024\"))) |>\n",
        "  # ensuring drug names fit on y axi\n",
        "  mutate(DRUG_CLASS = if_else(DRUG_CLASS == \"Third Generation Cephalosporins\", \"Third Generation\\nCephalosporins\", DRUG_CLASS)) |>\n",
        "  # plotting\n",
        "  ggplot(aes(x=time,\n",
        "             y=nonsusceptible,\n",
        "             colour=ORGANISM_OR_BUG,\n",
        "             shape=dataset\n",
        "             )) +\n",
        "  #geom_point(aes(size=total_CLASS),\n",
        "             #alpha=0.8) +\n",
        "  geom_line(aes(linetype = dataset),alpha=0.8) +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Resistance (%)\",\n",
        "       colour = \"Organism\",\n",
        "       linetype = \"Data\",\n",
        "       shape=\"Dataset\",\n",
        "       size = \"Isolate Count\") +\n",
        "  guides(colour=\"none\") +\n",
        "  theme_bw() +\n",
        "  theme(  axis.title.x = element_text(vjust = -2),\n",
        "          axis.title.y = element_text(vjust = 2),\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11),\n",
        "          strip.text.x = element_text(face = \"italic\"),\n",
        "          strip.background = element_blank()\n",
        "       ) +\n",
        "  facet_grid(DRUG_CLASS~ORGANISM_OR_BUG) +\n",
        "  scale_colour_manual(values = c(\"#008080\",\"#FFA500\")) +\n",
        "  scale_y_continuous(limits = c(0,100), labels = function(x)paste0(x,\"%\")) +\n",
        "  # enforcing ylim\n",
        "  #guides(colour = guide_legend(order = 1)) +\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) #+\n",
        "  # second national lockdown date\n",
        "  #geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             #linetype = \"dashed\",\n",
        "             #color = \"grey\",\n",
        "             #alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  #geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             #linetype = \"dashed\",\n",
        "             #color = \"grey\",\n",
        "             #alpha=0.8)\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/14_micro_cf_BLOOD_resistance_Kpn_Ec_ESPAUR_yearly.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/14_micro_cf_BLOOD_resistance_Kpn_Ec_ESPAUR_quarterly.jpeg\",\n",
        "       #height= 8,\n",
        "       #width=30)\n",
        "     \n",
        "png(\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       width=8.27,\n",
        "       height=11.69,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# joining ukhsa data with bld_data data\n",
        "\n",
        "## tidying ukhsa data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751120611364
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "#kable(ukhsa_data)\n",
        "ukhsa_data <-\n",
        "ukhsa_data |>\n",
        "    # selecting columns of interest as they relate to the micro_cf_BLOOD data\n",
        "    select(ORGANISM_OR_BUG=Organism, \n",
        "           DRUG_CLASS=Antibiotic,\n",
        "           status=Source,\n",
        "           total_CLASS=Tested,\n",
        "           nonsusceptible=`Resistant....`\n",
        "           ) |>\n",
        "    # renaming factor levels\n",
        "    mutate(status = fct_recode(status, \n",
        "                               \"Hospital Onset\"=\"HA\",\n",
        "                               \"Community Onset\"=\"CA\")) |>\n",
        "    mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG == \"E. coli\",\"Escherichia coli\",\"Klebsiella pneumoniae\")) |>\n",
        "    # reclassifying columns\n",
        "    mutate(ORGANISM_OR_BUG = as.factor(ORGANISM_OR_BUG),\n",
        "           DRUG_CLASS = as.factor(str_to_title(DRUG_CLASS))) |>\n",
        "    # changing pip-taz to TAZOCIN & 3rd gen cephalosporions\n",
        "    mutate(DRUG_CLASS = str_replace(DRUG_CLASS,\"Piperacillin-Tazobactam\", \"Tazocin\")) |>\n",
        "    mutate(DRUG_CLASS = str_replace(DRUG_CLASS,\"3rd Gen Cephalosporins\", \"Third Generation Cephalosporins\")) |>\n",
        "    # creating time column\n",
        "    slice(rep(1:n(), each = 3)) |>\n",
        "    mutate(time = rep(as.Date(c(\"2020-04-01\",\"2021-03-15\",\"2022-03-01\")), times = n()/3)) |>\n",
        "    # halving total for each tested count (across two timepoints) - just so it looks better visually\n",
        "    mutate(total_CLASS = total_CLASS / 2) |>\n",
        "    # creating column to differentiate data\n",
        "    mutate(dataset = \"UKHSA 2025\") |>\n",
        "    # reordering columns\n",
        "    relocate(time, .before = status)\n",
        "#kable(ukhsa_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## tidying bld_data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751120619990
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "to_bind <-\n",
        "bld_data |>\n",
        "  # filtering for bugs of interest\n",
        "  filter(ORGANISM_OR_BUG==\"Escherichia coli\" |\n",
        "           ORGANISM_OR_BUG==\"Klebsiella pneumoniae\") |>\n",
        "  # filtering for drugs of interest & those mentioned in UKHSA report\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # renaming factor levels\n",
        "  mutate(status = if_else(str_detect(AFTER_48HRS,\"after\"), \"Hospital Onset\", \"Community Onset\")) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         ORGANISM_OR_BUG,\n",
        "         status,\n",
        "         DRUG,\n",
        "         DECODED) |>\n",
        "  # creating time interval column\n",
        "  mutate(\n",
        "    # uncomment depending on time interval selection: name must match espaur data\n",
        "    time=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"year\"),\n",
        "    #time=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"quarter\"),\n",
        "    # reclassiyfing drugs per UKHSA report\n",
        "    DRUG_CLASS = case_when(\n",
        "        # aminoglycosides\n",
        "        DRUG %in% c(\"AMIKACIN\", \"GENTAMICIN\", \"TOBRAMYCIN\",\"NEOMYCIN\",\"SPECTINOMYCIN\",\"STREPTOMYCIN\",\"KANAMYCIN\") ~ \"Aminoglycosides\",\n",
        "        # carbapenems\n",
        "        DRUG %in% c(\"ERTAPENEM\",\"IMIPENEM\",\"MEROPENEM\") ~ \"Carbapenems\",\n",
        "        # third generation cephalosporins\n",
        "        DRUG %in% c(\"CEFOTAXIME\", \"CEFTAZIDIME\") ~ \"Third Generation Cephalosporins\",\n",
        "        TRUE ~ str_to_title(DRUG))\n",
        "        ) |>\n",
        "  # counting total bugs-drug combinations per time interval by drug\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           status,\n",
        "           time,\n",
        "           DRUG) |>\n",
        "  # creating total count column\n",
        "  mutate(\n",
        "         total_DRUG=n()\n",
        "         ) |>\n",
        "  ungroup() |>\n",
        "  # counting total bugs-drug combinations per time interval by drug class (UKHSA report)\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           status,\n",
        "           time,\n",
        "           DRUG_CLASS) |>\n",
        "  # creating total timely count column\n",
        "  mutate(\n",
        "        total_CLASS=n()\n",
        "        ) |>\n",
        "  ungroup() |>\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           status,\n",
        "           time,\n",
        "           DRUG_CLASS) |>\n",
        "  summarise(DECODED,\n",
        "            total_CLASS,\n",
        "            resistant_CLASS = sum(DECODED == \"Resistant\" |\n",
        "                                  DECODED == \"Intermediate\", na.rm = TRUE)) |>\n",
        "  ungroup() |>\n",
        "  select(-DECODED) |>\n",
        "  relocate(\n",
        "          time, .before = total_CLASS\n",
        "          ) |>\n",
        "  distinct() |>\n",
        "  # calculating percentage\n",
        "  mutate(nonsusceptible = (resistant_CLASS/total_CLASS)*100) |>\n",
        "  # creating column to differentiate data\n",
        "  mutate(dataset = \"iCARE\") |>\n",
        "        select(ORGANISM_OR_BUG,\n",
        "               DRUG_CLASS,\n",
        "               status,\n",
        "               total_CLASS,\n",
        "               nonsusceptible,\n",
        "               time,\n",
        "               dataset)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## visually checking data align"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751118621690
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "kable(ukhsa_data)\n",
        "kable(to_bind)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## binding both datasets"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751120631722
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "ukhsa_data <- rbind(ukhsa_data,to_bind)\n",
        "#kable(ukhsa_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting K. pneumoniae yearly resistance rates selected drugs: bld_data vs ukhsa data\n",
        "\n",
        "## 15. line chart\n",
        "### HO vs CO, Kpn only"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751121303073
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# line chart\n",
        "ukhsa_data |>\n",
        "  # filtering for bug of interest\n",
        "  #filter(\n",
        "        #ORGANISM_OR_BUG==\"Escherichia coli\" #|\n",
        "        #ORGANISM_OR_BUG==\"Klebsiella pneumoniae\"\n",
        "        #) |>\n",
        "  # filtering out total count\n",
        "  filter(status != \"Total\") |>\n",
        "  # filtering for drugs of interest (defined by UKHSA)\n",
        "  filter(DRUG_CLASS %in% c(\"Co-Amoxiclav\", \"Aminoglycosides\", \"Ciprofloxacin\", \"Carbapenems\", \"Tazocin\", \"Third Generation Cephalosporins\")) |>\n",
        "  # ensuring drug names fit on y axi\n",
        "  mutate(DRUG_CLASS = if_else(DRUG_CLASS == \"Third Generation Cephalosporins\", \"Third Generation\\nCephalosporins\", DRUG_CLASS)) |>\n",
        "  # plotting\n",
        "  ggplot(aes(x=time,\n",
        "             y=nonsusceptible,\n",
        "             colour=status,\n",
        "             #shape=dataset\n",
        "             )) +\n",
        "  #geom_point(aes(size=total_CLASS),\n",
        "             #alpha=0.8) +\n",
        "  geom_line(aes(linetype = dataset),alpha=0.8) +\n",
        "  scale_linetype_manual(values = c(\"solid\", \"dotdash\")) +\n",
        "  scale_y_continuous(limits = c(0,100), labels = function(x)paste0(x,\"%\")) +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Resistance (%)\",\n",
        "       colour = \"Infection Category\",\n",
        "       linetype = \"Data\",\n",
        "       shape=\"Dataset\",\n",
        "       size = \"Isolate Count\") +\n",
        "  #guides(linetype=\"none\") +\n",
        "  theme_bw() +\n",
        "  theme(  axis.title.x = element_text(vjust = -2),\n",
        "          axis.title.y = element_text(vjust = 2),\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11),\n",
        "          strip.text.x = element_text(face = \"italic\"),\n",
        "          strip.background = element_blank()\n",
        "       ) +\n",
        "  facet_grid(DRUG_CLASS~ORGANISM_OR_BUG)\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/15_bld_data_resistance_Kpn_ONLY_UKHSA_quarterly.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/15_bld_data_resistance_Ec_ONLY_UKHSA_quarterly.jpeg\",\n",
        "       #height= 8,\n",
        "       #width=20)\n",
        "\n",
        "png(\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       width=8.27,\n",
        "       height=10.02,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting K. pneumoniae yearly resistance rates selected drugs: micro_cf_BLOOD vs espaur data vs ukhsa data\n",
        "\n",
        "## tidying data\n",
        "\n",
        "### micro_cf_BLOOD"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751121512950
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "to_bind <-\n",
        "micro_cf_BLOOD |>\n",
        "  # filtering for bugs of interest\n",
        "  filter(ORGANISM_OR_BUG==\"Escherichia coli\" |\n",
        "           ORGANISM_OR_BUG==\"Klebsiella pneumoniae\") |>\n",
        "  # filtering for drugs of interest (defined in 4. GLMM)\n",
        "  filter(DRUG %in% drugs_of_interest) |>\n",
        "  # removing additional drugs not mentioned in ESPAUR\n",
        "  filter(!DRUG %in% c(\"AMOXYCILLIN\",\"COTRIMOXAZOLE\",\"TEMOCILLIN\")) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         ORGANISM_OR_BUG,\n",
        "         DRUG,\n",
        "         DECODED) |>\n",
        "  # creating time interval column\n",
        "  mutate(\n",
        "    # uncomment depending on time interval selection: name must match espaur data\n",
        "    time=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"year\"),\n",
        "    #time=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"quarter\"),\n",
        "    # reclassiyfing drugs per ESPAUR report & UKHSA report\n",
        "    DRUG_CLASS = case_when(\n",
        "        # aminoglycosides\n",
        "        DRUG %in% c(\"AMIKACIN\", \"GENTAMICIN\", \"TOBRAMYCIN\",\"NEOMYCIN\",\"SPECTINOMYCIN\",\"STREPTOMYCIN\",\"KANAMYCIN\") ~ \"Aminoglycosides\",\n",
        "        # carbapenems\n",
        "        DRUG %in% c(\"ERTAPENEM\",\"IMIPENEM\",\"MEROPENEM\") ~ \"Carbapenems\",\n",
        "        # third generation cephalosporins\n",
        "        DRUG %in% c(\"CEFOTAXIME\", \"CEFTAZIDIME\", \"CEFPODOXIME\",\"CEFTRIAXONE\") ~ \"Third Generation Cephalosporins\",\n",
        "        TRUE ~ str_to_title(DRUG))\n",
        "        ) |>\n",
        "  # counting total bugs-drug combinations per time interval by drug\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           time,\n",
        "           DRUG) |>\n",
        "  # creating total count column\n",
        "  mutate(\n",
        "         total_DRUG=n()\n",
        "         ) |>\n",
        "  ungroup() |>\n",
        "  # counting total bugs-drug combinations per time interval by drug class (ESPAUR report)\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           time,\n",
        "           DRUG_CLASS) |>\n",
        "  # creating total timely count column\n",
        "  mutate(\n",
        "        total_CLASS=n()\n",
        "        ) |>\n",
        "  ungroup() |>\n",
        "  group_by(ORGANISM_OR_BUG,\n",
        "           time,\n",
        "           DRUG_CLASS) |>\n",
        "  summarise(DECODED,\n",
        "            total_CLASS,\n",
        "            resistant_CLASS = sum(DECODED == \"Resistant\" |\n",
        "                                  DECODED == \"Intermediate\", na.rm = TRUE)) |>\n",
        "  select(-DECODED) |>\n",
        "  relocate(\n",
        "          time, .before = total_CLASS\n",
        "          ) |>\n",
        "  distinct() |>\n",
        "  # creating column to differentiate data\n",
        "  mutate(dataset = \"iCARE\") |>\n",
        "  mutate(nonsusceptible = (resistant_CLASS/total_CLASS)*100) |>\n",
        "  select(-resistant_CLASS) |>\n",
        "  relocate(nonsusceptible, .before = dataset)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "### ukhsa and espaur data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751121516998
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "all_national <- ukhsa_data |>\n",
        "                 filter(status == \"Total\") |>\n",
        "                 select(-status)\n",
        "\n",
        "espaur_data <- espaur_data |>\n",
        "            select(-c(resistant_CLASS)) |>\n",
        "            relocate(dataset, .after = nonsusceptible)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## visually checking data align"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1746788058627
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "kable(to_bind)\n",
        "kable(all_national)\n",
        "kable(espaur_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## binding datasets"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751121522381
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "all_national <- rbind(all_national,to_bind)\n",
        "all_national <- rbind(all_national, espaur_data)\n",
        "\n",
        "#kable(all_national)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751121524687
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "all_national |>\n",
        "group_by(dataset) |>\n",
        "tally()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## plotting\n",
        "\n",
        "### 16. line chart"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751121699374
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "all_national |>\n",
        "  # filtering for bug of interest\n",
        "  #filter(\n",
        "        #ORGANISM_OR_BUG==\"Escherichia coli\" #|\n",
        "        #ORGANISM_OR_BUG==\"Klebsiella pneumoniae\"\n",
        "        #) |>\n",
        "  # ordering\n",
        "  mutate(dataset = factor(dataset, levels = c(\"iCARE\",\"ESPAUR 2024\", \"UKHSA 2025\"))) |>\n",
        "  # ensuring drug names fit on y axi\n",
        "  mutate(DRUG_CLASS = if_else(DRUG_CLASS == \"Third Generation Cephalosporins\", \"Third Generation\\nCephalosporins\", DRUG_CLASS)) |>\n",
        "  # plotting\n",
        "  ggplot(aes(x=time,\n",
        "             y=nonsusceptible,\n",
        "             colour=ORGANISM_OR_BUG,\n",
        "             shape=dataset\n",
        "             )) +\n",
        "  #geom_point(aes(size=total_CLASS),\n",
        "             #alpha=0.8) +\n",
        "  geom_line(aes(linetype = dataset),alpha=0.8) +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Resistance (%)\",\n",
        "       #colour = \"Dataset\",\n",
        "       linetype = \"Data\",\n",
        "       #size = \"Isolate Count\"\n",
        "       ) +\n",
        "  scale_linetype_manual(values = c(\"solid\",\"dashed\",\"dotdash\")) +\n",
        "  guides(colour=\"none\")+\n",
        "  theme_bw() +\n",
        "  theme(  axis.title.x = element_text(vjust = -2),\n",
        "          axis.title.y = element_text(vjust = 2),\n",
        "          # add legend box\n",
        "          legend.background=element_blank(),\n",
        "          legend.box.background=element_rect(colour = \"black\"),\n",
        "          # ensuring even legend border\n",
        "          legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "          # strips\n",
        "          strip.text = element_text(size=11),\n",
        "          strip.text.x = element_text(face = \"italic\"),\n",
        "          strip.background = element_blank()\n",
        "       ) +\n",
        "  facet_grid(DRUG_CLASS~ORGANISM_OR_BUG) +\n",
        "  #scale_colour_igv() +\n",
        "  scale_colour_manual(values = c(\"#008080\",\"#FFA500\")) +\n",
        "  scale_y_continuous(limits = c(0,100), labels = function(x)paste0(x,\"%\")) +\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             alpha=0.8) #+\n",
        "  # second national lockdown date\n",
        "  #geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             #linetype = \"dashed\",\n",
        "             #color = \"grey\",\n",
        "             #alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  #geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             #linetype = \"dashed\",\n",
        "             #color = \"grey\",\n",
        "             #alpha=0.8)\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/16_micro_cf_BLOOD_resistance_Kpn_Ec_ESPAUR_UKHSA_yearly.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/16_micro_cf_BLOOD_resistance_Kpn_ONLY_ESPAUR_UKHSA_yearly.jpeg\",\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/16_micro_cf_BLOOD_resistance_Ec_ONLY_ESPAUR_UKHSA_yearly.jpeg\",\n",
        "       #height= 7,\n",
        "       #width=30)\n",
        "\n",
        "png(\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       width=8.27,\n",
        "       height=11.69,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# **<<< 7. INVESTIGATING MULTI-DRUG RESISTANCE >>>**\n",
        "\n",
        "# creating upset data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754395093574
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "upset <-\n",
        "#micro_cf_ALL |>\n",
        "micro_cf_BLOOD |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # grouping other Enterobacteriaceae in \"Other\" category\n",
        "  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c(\"Escherichia coli\",\"Klebsiella pneumoniae\"), \n",
        "         ORGANISM_OR_BUG, \"Other Enterobacteriaceae\")) |>\n",
        "    select(SUBJECT,\n",
        "           SAMPLE_COLLECTED_DT,\n",
        "           ORGANISM_OR_BUG,\n",
        "           DRUG,\n",
        "           DRUG_CLASS,\n",
        "           DECODED) |>\n",
        "    mutate(DECODED_2 = DECODED %in% c(\"Resistant\",\"Intermediate\")) |>\n",
        "    select(-c(DECODED,DRUG_CLASS)) |>\n",
        "    filter(DRUG %in% drugs_of_interest) |>\n",
        "    distinct() |>\n",
        "    #group_by(SUBJECT,SAMPLE_COLLECTED_DT,ORGANISM_OR_BUG)|>\n",
        "    pivot_wider(names_from = DRUG,\n",
        "                values_from = DECODED_2,\n",
        "                values_fn = list(DECODED_2 = any),\n",
        "                values_fill = list(DECODED_2 = FALSE)) |>\n",
        "                # converting to 1,0 binary\n",
        "    mutate(across(`CO-AMOXICLAV`:GENTAMICIN, ~as.integer(.)))\n",
        "\n",
        "colnames(upset)[4:15] <- str_to_title(colnames(upset)[4:15])\n",
        "\n",
        "upset"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## filtering for MDR profiles only\n",
        "### **BE AWARE OF THIS IN DOWNSTREAM ANALYSES**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754395097382
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# converting binary to logical\n",
        "upset <-\n",
        "upset |>\n",
        "    mutate(across(`Co-Amoxiclav`:Gentamicin, ~as.logical(.))) |>\n",
        "    # filtering singular resistances and empty rows\n",
        "    filter(rowSums(across(`Co-Amoxiclav`:Gentamicin, ~ .)) > 1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting MDR upset data across all organisms"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754392673589
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# ordering sets\n",
        "sets_ordered <- c(\n",
        "       \"Amikacin\",\n",
        "       \"Gentamicin\",\n",
        "       \"Ertapenem\",\n",
        "       \"Meropenem\",\n",
        "       \"Ceftazidime\",\n",
        "       \"Ceftriaxone\",\n",
        "       \"Ciprofloxacin\",\n",
        "       \"Amoxycillin\",\n",
        "       \"Co-Amoxiclav\",\n",
        "       \"Tazocin\",\n",
        "       \"Temocillin\",\n",
        "       \"Cotrimoxazole\"\n",
        "  )\n",
        "\n",
        "# ordering columns\n",
        "upset <- upset[, c(colnames(upset)[1:3], rev(sets_ordered))]\n",
        "\n",
        "sets <- as.character(colnames(upset)[4:15])\n",
        "\n",
        "# focussing on exclusive interactions\n",
        "presence = ComplexUpset:::get_mode_presence(\"exclusive_intersection\")\n",
        "\n",
        "summarise_values = function(df) {\n",
        "       aggregate(\n",
        "              as.formula(paste0(presence, \"~ intersection\")),\n",
        "              df,\n",
        "              FUN=sum\n",
        "       )\n",
        "}\n",
        "\n",
        "# plotting data across all organisms\n",
        "ComplexUpset:::upset(as.data.frame(upset),\n",
        "      sets,\n",
        "      sort_sets = FALSE,\n",
        "      stripes=\"white\",\n",
        "      name = \"\\n Phenotypic Resistance Profile\",\n",
        "      width_ratio = 0.2,\n",
        "      height_ratio = 1.5,\n",
        "      min_size=50,\n",
        "      base_annotations=list(\n",
        "       \"Count\"=(\n",
        "              ggplot() +\n",
        "              geom_bar(data=summarise_values,\n",
        "                       stat=\"identity\",\n",
        "                       aes(y=!!presence),\n",
        "                       alpha=0.8,\n",
        "                       fill=\"#008080\") +\n",
        "                       ylab(\"Isolate Count\"))),\n",
        "      annotations=list(\n",
        "       \"Organism\"=(\n",
        "              ggplot(mapping=aes(fill=as.factor(ORGANISM_OR_BUG))) +\n",
        "              geom_bar(stat=\"count\",position=\"fill\",alpha=0.8) +\n",
        "              scale_y_continuous(labels=function(x) paste0(x*100,\"%\")) +\n",
        "              scale_fill_manual(values = c(\"#008080\",\"#FFA500\",\"#708090\")) +\n",
        "              labs(y=\"Proportion (%)\", fill = \"Organism\") +\n",
        "              theme(axis.title.y=element_text(vjust=1),\n",
        "                    legend.text = element_text(size=11,face = \"italic\"))\n",
        "              )),\n",
        "      set_sizes=(upset_set_size(\n",
        "       geom=geom_bar(width=0.8, aes(y=..count..),\n",
        "                                    alpha=0.8)) +\n",
        "       ylab(\"\\nIsolate Count\")),\n",
        "      queries = list(\n",
        "       upset_query(set=\"Amikacin\", fill=\"#3B4992CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Gentamicin\", fill=\"#3B4992CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ertapenem\", fill=\"#EE0000CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Meropenem\", fill=\"#EE0000CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ceftazidime\", fill=\"#008B45CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ceftriaxone\", fill=\"#008B45CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ciprofloxacin\", fill=\"#631879CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Amoxycillin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Co-Amoxiclav\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Tazocin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Temocillin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Cotrimoxazole\", fill=\"#A20056CC\", color_by=\"fill\")\n",
        "      )\n",
        "      )\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #height= 8,\n",
        "       #width=20)\n",
        "\n",
        "png(\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/upset_all.jpeg\",\n",
        "       height=8.27,\n",
        "       width=11.69,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting MDR upset data for individual organisms"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754393374456
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# ordering sets\n",
        "sets_ordered <- c(\n",
        "       \"Amikacin\",\n",
        "       \"Gentamicin\",\n",
        "       \"Ertapenem\",\n",
        "       \"Meropenem\",\n",
        "       \"Ceftazidime\",\n",
        "       \"Ceftriaxone\",\n",
        "       \"Ciprofloxacin\",\n",
        "       \"Amoxycillin\",\n",
        "       \"Co-Amoxiclav\",\n",
        "       \"Tazocin\",\n",
        "       \"Temocillin\",\n",
        "       \"Cotrimoxazole\"\n",
        "  )\n",
        "\n",
        "# ordering columns\n",
        "upset <- upset[, c(colnames(upset)[1:3], rev(sets_ordered))]\n",
        "\n",
        "sets <- as.character(colnames(upset)[4:15])\n",
        "\n",
        "# focussing on exclusive interactions\n",
        "presence = ComplexUpset:::get_mode_presence(\"exclusive_intersection\")\n",
        "\n",
        "summarise_values = function(df) {\n",
        "       aggregate(\n",
        "              as.formula(paste0(presence, \"~ intersection\")),\n",
        "              df,\n",
        "              FUN=sum\n",
        "       )\n",
        "}\n",
        "\n",
        "# plotting data across all organisms\n",
        "ComplexUpset:::upset(as.data.frame(upset[upset$ORGANISM_OR_BUG==#\"Klebsiella pneumoniae\",\n",
        "                                                              #\"Escherichia coli\",\n",
        "                                                              \"Other Enterobacteriaceae\",\n",
        "                    ]),\n",
        "      sets,\n",
        "      sort_sets = FALSE,\n",
        "      stripes=\"white\",\n",
        "      name = \"\\n Phenotypic Resistance Profile\",\n",
        "      width_ratio = 0.2,\n",
        "      height_ratio = 1.5,\n",
        "      min_size=10,\n",
        "      #min_size=25,\n",
        "      base_annotations=list(\n",
        "       \"Count\"=(\n",
        "              ggplot() +\n",
        "              geom_bar(data=summarise_values,\n",
        "                       stat=\"identity\",\n",
        "                       aes(y=!!presence),\n",
        "                       alpha=0.8,\n",
        "                       fill=#\"#FFA500\" # Kpn\n",
        "                            #\"#008080\" # Ec\n",
        "                            \"#708090\" # Other Eb\n",
        "                     ) +\n",
        "                       ylab(\"Isolate Count\"))),\n",
        "      set_sizes=(upset_set_size(\n",
        "       geom=geom_bar(width=0.8, aes(y=..count..),\n",
        "                                    alpha=0.8)) +\n",
        "       ylab(\"\\nIsolate Count\")),\n",
        "      queries = list(\n",
        "       upset_query(set=\"Amikacin\", fill=\"#3B4992CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Gentamicin\", fill=\"#3B4992CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ertapenem\", fill=\"#EE0000CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Meropenem\", fill=\"#EE0000CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ceftazidime\", fill=\"#008B45CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ceftriaxone\", fill=\"#008B45CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ciprofloxacin\", fill=\"#631879CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Amoxycillin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Co-Amoxiclav\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Tazocin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Temocillin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Cotrimoxazole\", fill=\"#A20056CC\", color_by=\"fill\")\n",
        "      )\n",
        "      )\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #height= 8,\n",
        "       #width=20)\n",
        "\n",
        "png(\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/upset_kpn.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/upset_ec.jpeg\",\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/upset_oe.jpeg\",\n",
        "       height=8.27,\n",
        "       width=11.69,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting MDR profiles across time\n",
        "\n",
        "## working out top 5 Kpn MDR profiles"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754393429613
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "# plotting data across all organisms\n",
        "ComplexUpset:::upset(as.data.frame(upset[upset$ORGANISM_OR_BUG==\"Klebsiella pneumoniae\",\n",
        "                                                              #\"Escherichia coli\",\n",
        "                                                              #\"Other Enterobacteriaceae\",\n",
        "                    ]),\n",
        "      sets,\n",
        "      sort_sets = FALSE,\n",
        "      stripes=\"white\",\n",
        "      name = \"\\n Phenotypic Resistance Profile\",\n",
        "      width_ratio = 0.2,\n",
        "      height_ratio = 1.5,\n",
        "      min_size=45,\n",
        "      base_annotations=list(\n",
        "       \"Count\"=(\n",
        "              ggplot() +\n",
        "              geom_bar(data=summarise_values,\n",
        "                       stat=\"identity\",\n",
        "                       aes(y=!!presence),\n",
        "                       alpha=0.8,\n",
        "                       fill=\"#FFA500\" # Kpn\n",
        "                            #\"#008080\" # Ec\n",
        "                            #\"#708090\" # Other Eb\n",
        "                     ) +\n",
        "                       ylab(\"Number of Isolates\"))),\n",
        "      set_sizes=(upset_set_size(\n",
        "       geom=geom_bar(width=0.8, aes(y=..count..),\n",
        "                                    alpha=0.8)) +\n",
        "       ylab(\"\\nNumber of Isolates\")),\n",
        "      queries = list(\n",
        "       upset_query(set=\"Amikacin\", fill=\"#3B4992CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Gentamicin\", fill=\"#3B4992CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ertapenem\", fill=\"#EE0000CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Meropenem\", fill=\"#EE0000CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ceftazidime\", fill=\"#008B45CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ceftriaxone\", fill=\"#008B45CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ciprofloxacin\", fill=\"#631879CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Amoxycillin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Co-Amoxiclav\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Tazocin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Temocillin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Cotrimoxazole\", fill=\"#A20056CC\", color_by=\"fill\")\n",
        "      )\n",
        "      )\n",
        "\n",
        "png(\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       height=8.27,\n",
        "       width=11.69,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## Kpn top MDR profiles\n",
        "### 1. Gentamicin (Aminoglycosides) - Ceftazidime & Ceftriaxone (Cephalosporins) - Ciprofloxacin (Fluoroquinolones) - Amoxycillin & Co-Amoxiclav & Tazocin (Penicillins) & Cotrimoxazole (Sulfonamides)\n",
        "### 2. Ceftazidime & Ceftriaxone (Cephalosporins) - Ciprofloxacin (Fluoroquinolones) - Amoxycillin & Co-Amoxiclav & Tazocin (Penicillins) & Cotrimoxazole (Sulfonamides)\n",
        "### 3. Ertapenem (Carbapenems) - Ceftazidime & Ceftriaxone (Cephalosporins) - Ciprofloxacin (Fluoroquinolones) - Amoxycillin & Temocillin (Penicillins)\n",
        "### 4. All drugs\n",
        "### 5. Ceftazidime & Ceftriaxone (Cephalosporins) - Amoxycillin & Co-Amoxiclav (Penicillins) -  Cotrimoxazole (Sulfonamides)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754393621625
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "upset |>\n",
        "    rowwise()|>\n",
        "    mutate(MDR = case_when(\n",
        "         Amikacin & Gentamicin & Ertapenem & Meropenem & Ceftazidime & Ceftriaxone & Ciprofloxacin & Amoxycillin & `Co-Amoxiclav` & Tazocin & Temocillin & Cotrimoxazole ~ \"PDR\", # largest group must be first per case_when()\n",
        "         Gentamicin & Ceftazidime & Ceftriaxone & Ciprofloxacin & Amoxycillin & `Co-Amoxiclav` & Tazocin & Cotrimoxazole ~ \"MDR 1\",\n",
        "         Ceftazidime & Ceftriaxone & Ciprofloxacin & Amoxycillin & `Co-Amoxiclav` & Tazocin & Cotrimoxazole ~ \"MDR 2\",\n",
        "         Ertapenem & Ceftazidime & Ceftriaxone & Ciprofloxacin & Amoxycillin & Temocillin ~ \"MDR 3\",\n",
        "         Ceftazidime & Ceftriaxone & Amoxycillin & `Co-Amoxiclav` & Cotrimoxazole ~ \"MDR 4\",\n",
        "         TRUE ~ NA_character_\n",
        "    )) |>\n",
        "  ungroup() |>\n",
        "  # filtering for Kpn\n",
        "  filter(ORGANISM_OR_BUG == \"Klebsiella pneumoniae\") |>\n",
        "  # filtering NAs\n",
        "  filter(!is.na(MDR)) |>\n",
        "  # creating month column\n",
        "  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"quarter\")) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(MONTH < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(\n",
        "    MDR,\n",
        "    MONTH\n",
        "  ) |>\n",
        "  tally() |>\n",
        "ggplot(aes(x=MONTH,\n",
        "           y=n,\n",
        "           colour=MDR)) +\n",
        "  geom_line(alpha=0.8) +\n",
        "  # first national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-03-23\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # second national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2020-11-05\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  # third national lockdown date\n",
        "  geom_vline(xintercept=as.Date(\"2021-01-06\"),\n",
        "             linetype = \"dashed\",\n",
        "             color = \"grey\",\n",
        "             size=0.3,\n",
        "             alpha=0.8) +\n",
        "  labs(x = \"Date\",\n",
        "       y = \"Isolate Count\",\n",
        "       colour = \"Multi-Drug Resistance Profile\") +\n",
        "  theme_bw() +\n",
        "  scale_colour_bmj() +\n",
        "  # sizing\n",
        "  theme(axis.title.x = element_text(vjust = -2),\n",
        "        axis.title.y = element_text(vjust = 2),\n",
        "        # add legend box\n",
        "        legend.background=element_blank(),\n",
        "        # legend text\n",
        "        legend.text = element_text(size=11), \n",
        "        # ensuring even legend border\n",
        "        legend.margin=margin(4,4,4,4, unit = \"mm\"),\n",
        "        legend.box.background=element_rect(colour = \"black\"),\n",
        "        legend.title = element_text(size=11))\n",
        "\n",
        "png(\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/Kpn_quarterly_MDR_profiles.jpeg\",\n",
        "       height=3,\n",
        "       width=8,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# investigating co-occurrence of resistance phenotypes"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754394724629
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "cooccurrence <-upset  |>\n",
        "    # converting to 1,0 binary\n",
        "    mutate(across(`Co-Amoxiclav`:Gentamicin, ~as.integer(.))) |>\n",
        "    select(`Co-Amoxiclav`:Gentamicin) |>\n",
        "    as.matrix() #|>\n",
        "    #crossprod()\n",
        "\n",
        "cooccurrence\n",
        "\n",
        "corrplot::corrplot(cor(cooccurrence), method = \"square\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# investigating multi-level associations"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754395314987
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "mca <-\n",
        "upset |>\n",
        "    select(ORGANISM_OR_BUG,`Co-Amoxiclav`:Gentamicin) |>\n",
        "    mutate(across(-ORGANISM_OR_BUG, as.factor)) #|>\n",
        "    # filtering by bug\n",
        "    #filter(ORGANISM_OR_BUG == \"Klebsiella pneumoniae\")\n",
        "\n",
        "# mca results FactoMineR\n",
        "mca_results <- MCA(mca, graph = FALSE, \n",
        "        # comment-out below if bug specific\n",
        "        quali.sup=1\n",
        "        )\n",
        "\n",
        "true_vars <- grep(\"_TRUE$\", rownames(mca_results$var$coord), value = TRUE)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754395216393
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "mca"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754395322958
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "mca_results$eig[1:5, ]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754395394911
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "fviz_mca_var(mca_results, \n",
        "             select.var = list(name = true_vars),\n",
        "             repel = TRUE,\n",
        "             col.var = \"contrib\")\n",
        "\n",
        "png(\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/new.jpeg\",\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/All_MCA_plot.jpeg\",\n",
        "       #filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting_final_August2025/Kpn_MCA_plot.jpeg\",\n",
        "       height=8,\n",
        "       width=6,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# plotting upset data for Kpn blood isolates, April 2020 - December 2021"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751267707509
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "upset <- upset |>\n",
        "  # filtering for April 2020 - December 2021\n",
        "  filter(SAMPLE_COLLECTED_DT >= as.Date(\"2020-04-01\") & SAMPLE_COLLECTED_DT <= as.Date(\"2021-12-31\"))\n",
        "\n",
        "# ordering sets\n",
        "sets_ordered <- c(\n",
        "       \"Amikacin\",\n",
        "       \"Gentamicin\",\n",
        "       \"Ertapenem\",\n",
        "       \"Meropenem\",\n",
        "       \"Ceftazidime\",\n",
        "       \"Ceftriaxone\",\n",
        "       \"Ciprofloxacin\",\n",
        "       \"Amoxycillin\",\n",
        "       \"Co-Amoxiclav\",\n",
        "       \"Tazocin\",\n",
        "       \"Temocillin\",\n",
        "       \"Cotrimoxazole\"\n",
        "  )\n",
        "\n",
        "# ordering columns\n",
        "upset <- upset[, c(colnames(upset)[1:3], rev(sets_ordered))]\n",
        "\n",
        "sets <- as.character(colnames(upset)[4:15])\n",
        "\n",
        "# focussing on exclusive interactions\n",
        "presence = ComplexUpset:::get_mode_presence(\"exclusive_intersection\")\n",
        "\n",
        "summarise_values = function(df) {\n",
        "       aggregate(\n",
        "              as.formula(paste0(presence, \"~ intersection\")),\n",
        "              df,\n",
        "              FUN=sum\n",
        "       )\n",
        "}\n",
        "\n",
        "# plotting data across all organisms\n",
        "ComplexUpset:::upset(as.data.frame(upset[upset$ORGANISM_OR_BUG==\"Klebsiella pneumoniae\",]),\n",
        "      sets,\n",
        "      sort_sets = FALSE,\n",
        "      stripes=\"white\",\n",
        "      name = \"\\n Phenotypic Resistance Profile\",\n",
        "      width_ratio = 0.2,\n",
        "      height_ratio = 1.5,\n",
        "      min_size=5,\n",
        "      base_annotations=list(\n",
        "       \"Count\"=(\n",
        "              ggplot() +\n",
        "              geom_bar(data=summarise_values,\n",
        "                       stat=\"identity\",\n",
        "                       aes(y=!!presence),\n",
        "                       alpha=0.8,\n",
        "                       fill=\"#FFA500\" # Kpn\n",
        "                            #\"#008080\" # Ec\n",
        "                            #\"#708090\" # Other Eb\n",
        "                     ) +\n",
        "                       ylab(\"Number of Isolates\"))),\n",
        "      set_sizes=(upset_set_size(\n",
        "       geom=geom_bar(width=0.8, aes(y=..count..),\n",
        "                                    alpha=0.8)) +\n",
        "       ylab(\"\\nNumber of Isolates\")),\n",
        "      queries = list(\n",
        "       upset_query(set=\"Amikacin\", fill=\"#3B4992CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Gentamicin\", fill=\"#3B4992CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ertapenem\", fill=\"#EE0000CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Meropenem\", fill=\"#EE0000CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ceftazidime\", fill=\"#008B45CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ceftriaxone\", fill=\"#008B45CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Ciprofloxacin\", fill=\"#631879CC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Amoxycillin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Co-Amoxiclav\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Tazocin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Temocillin\", fill=\"#5F559BCC\", color_by=\"fill\"),\n",
        "       upset_query(set=\"Cotrimoxazole\", fill=\"#A20056CC\", color_by=\"fill\")\n",
        "      )\n",
        "      )\n",
        "\n",
        "#ggsave(plot=last_plot(),\n",
        "       #\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       #height= 8,\n",
        "       #width=20)\n",
        "\n",
        "png(\n",
        "       filename=\"/home/azureuser/cloudfiles/code/Users/jrodgus-icare/plotting/new.jpeg\",\n",
        "       height=5,\n",
        "       width=10,\n",
        "       units=\"in\",\n",
        "       res=300\n",
        ")\n",
        "print(last_plot())\n",
        "dev.off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# **<<< 8. DATA TABLES >>>**\n",
        "# overall summary tables\n",
        "## demographics"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1753097825542
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "table <-\n",
        "all_data |>\n",
        "#bld_data  |>\n",
        "# filtering for bugs of interest\n",
        "filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "    select(SUBJECT,\n",
        "           AGE_AT_ADMISSION,\n",
        "           sex=GENDER_DESC,\n",
        "           ETHNICITY_DESC) |>\n",
        "    mutate(sex = str_to_title(sex),\n",
        "           AGE_AT_ADMISSION = as.numeric(AGE_AT_ADMISSION)) |>\n",
        "    distinct() |>\n",
        "    mutate(\n",
        "           age_band = cut(\n",
        "            AGE_AT_ADMISSION,\n",
        "            breaks = c(-Inf, 1, 5, 9, 17, 25, 40, 65, 80, Inf),\n",
        "            lables = c(\"leq1\", \"2-5\", \" 6-9\", \"10-17\", \"18-25\", \"26-20\",\"41-65\", \"65-80\", \"80+\"),\n",
        "            right=TRUE\n",
        "           )\n",
        "    ) |>\n",
        "    filter(!is.na(age_band)) |>\n",
        "    count(age_band, sex) |>\n",
        "    pivot_wider(names_from = sex, values_from=n, values_fill = 0) |>\n",
        "    mutate(\n",
        "        M_pct = round(Male/sum(Male)*100, 1),\n",
        "        F_pct = round(Female/sum(Female)*100, 1),\n",
        "        Total = Male+Female,\n",
        "        Total_pct = round(Total/sum(Total)*100, 1)\n",
        "    )\n",
        "\n",
        "bind_rows(table, \n",
        "            table |>\n",
        "            summarise(across(-age_band, sum)) |>\n",
        "            mutate(age_band = \"Overall\")) |>\n",
        "            kable(align=\"lrrrrrr\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754388791317
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "all_data |>\n",
        "#bld_data  |>\n",
        "# filtering for bugs of interest\n",
        "filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  mutate(\n",
        "         # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\n",
        "            # else\n",
        "            \"Undefined\"))) |>\n",
        "    select(SUBJECT,\n",
        "           HO,\n",
        "           AGE_AT_ADMISSION,\n",
        "           sex=GENDER_DESC,\n",
        "           ETHNICITY_DESC) |>\n",
        "    mutate(sex = str_to_title(sex),\n",
        "           AGE_AT_ADMISSION = as.numeric(AGE_AT_ADMISSION)) |>\n",
        "    distinct() |>\n",
        "    mutate(\n",
        "           age_band = cut(\n",
        "            AGE_AT_ADMISSION,\n",
        "            breaks = c(-Inf, 1, 5, 9, 17, 25, 40, 65, 80, Inf),\n",
        "            lables = c(\"leq1\", \"2-5\", \" 6-9\", \"10-17\", \"18-25\", \"26-20\",\"41-65\", \"65-80\", \"80+\"),\n",
        "            right=TRUE\n",
        "           )\n",
        "    ) |>\n",
        "    #filter(!is.na(age_band)) |>\n",
        "    count(HO, age_band, sex) |>\n",
        "    pivot_wider(names_from = sex, values_from=n, values_fill = 0) |>\n",
        "    mutate(\n",
        "        M_pct = round(Male/sum(Male)*100, 1),\n",
        "        F_pct = round(Female/sum(Female)*100, 1),\n",
        "        Total = Male+Female,\n",
        "        Total_pct = round(Total/sum(Total)*100, 1)\n",
        "    ) |>\n",
        "    mutate(sum_male = sum(Male),\n",
        "           sum_female = sum(Female))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754385865507
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "all_data |>\n",
        "#bld_data  |>\n",
        "filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "    select(SUBJECT,\n",
        "           AGE_AT_ADMISSION,\n",
        "           sex=GENDER_DESC,\n",
        "           HO\n",
        "           ETHNICITY_DESC) |>\n",
        "    mutate(sex = str_to_title(sex),\n",
        "           AGE_AT_ADMISSION = as.numeric(AGE_AT_ADMISSION)) |>\n",
        "    distinct() |>\n",
        "    group_by(sex) |>\n",
        "    summarise(\n",
        "        mean=mean(AGE_AT_ADMISSION, na.rm = T),\n",
        "        median=median(AGE_AT_ADMISSION, na.rm = T),\n",
        "        range=range(AGE_AT_ADMISSION, na.rm = T)\n",
        "    )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## bugs"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1753098998021
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "#micro_cf_ALL |>\n",
        "micro_cf_BLOOD |>\n",
        "filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "    select(SUBJECT,\n",
        "           SAMPLE_COLLECTED_DT,\n",
        "           ORGANISM_OR_BUG) |>\n",
        "    distinct() |>\n",
        "    group_by(\n",
        "        ORGANISM_OR_BUG,\n",
        "        ) |>\n",
        "    tally()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751987414252
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "#micro_cf_ALL |>\n",
        "#micro_cf_BLOOD |>\n",
        "#all_data |>\n",
        "bld_data |>\n",
        "# defining hospital onset infections\n",
        "  mutate(\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\n",
        "            # else\n",
        "            \"Undefined\"))) |>\n",
        "filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "    select(SUBJECT,\n",
        "           SPELL_IDENTIFIER,\n",
        "           EPISODE_IDENTIFIER,\n",
        "           SAMPLE_COLLECTED_DT,\n",
        "           HO,\n",
        "           ORGANISM_OR_BUG) |>\n",
        "    distinct() |>\n",
        "    group_by(\n",
        "        ORGANISM_OR_BUG,\n",
        "        HO\n",
        "        ) |>\n",
        "    tally()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "# sustained spike in Kpn blood isolates from HO infections during the pandemic 01/2021-02/2021 - age/gender\n",
        "# spike in Klebsiella spp from HO infections during the same months - age/gender"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754497584223
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "bld_data  |>\n",
        "  # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # grouping other Enterobacteriaceae in \"Other\" category\n",
        "  mutate(ORGANISM_OR_BUG = if_else(ORGANISM_OR_BUG %in% c(\"Escherichia coli\",\"Klebsiella pneumoniae\"), \n",
        "         ORGANISM_OR_BUG, \"Other Enterobacteriaceae\")) |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         SPELL_IDENTIFIER,\n",
        "         EPISODE_IDENTIFIER,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         WITHIN_SPELL,\n",
        "         AFTER_48HRS,\n",
        "         ORGANISM_OR_BUG) |>\n",
        "  # removing duplicates\n",
        "  distinct() |>\n",
        "  # creating month column\n",
        "  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\"),\n",
        "         # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\n",
        "            # else\n",
        "            \"Undefined\"))) |>\n",
        "  # filtering incomplete end month\n",
        "  filter(MONTH < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(\n",
        "    ORGANISM_OR_BUG,\n",
        "    HO,\n",
        "    SUBJECT,\n",
        "    MONTH\n",
        "  ) |>\n",
        "  tally() |>\n",
        "  arrange(desc(n)) |>\n",
        "  filter(ORGANISM_OR_BUG==\"Klebsiella pneumoniae\",HO==\"Hospital Onset\",MONTH >= \"2021-01-01\",MONTH <= \"2021-02-28\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754496040854
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "bld_data |>\n",
        "    # filtering for HO infections & bug of interest\n",
        "    filter(!ORGANISM_OR_BUG %in% c(\"Klebsiella pneumoniae\",\"Escherichia coli\", \"Other, including Gram +ves\"), AFTER_48HRS == \"Collection after 48 hours of admission\") |>\n",
        "    select(SUBJECT,SPELL_IDENTIFIER, EPISODE_IDENTIFIER, OLD_BUGS, SAMPLE_COLLECTED_DT) |>\n",
        "    distinct() |>\n",
        "    #filter(SAMPLE_COLLECTED_DT >= \"2021-01-01\" & SAMPLE_COLLECTED_DT <= \"2021-04-30\") |> # Other Enterobacteriaceae spike jan-april 2021\n",
        "    filter(SAMPLE_COLLECTED_DT >= \"2020-04-01\" & SAMPLE_COLLECTED_DT <= \"2020-04-30\") |> # Other Enterobacteriaceae spike april 2020\n",
        "    group_by(OLD_BUGS) |>\n",
        "    tally()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1754496836451
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "table <-\n",
        "#all_data |>\n",
        "bld_data |>\n",
        "    # filtering for HO infections & bug of interest\n",
        "    filter(ORGANISM_OR_BUG==\"Escherichia coli\", AFTER_48HRS == \"Collection after 48 hours of admission\") |>\n",
        "    #filter(ORGANISM_OR_BUG==\"Klebsiella pneumoniae\", AFTER_48HRS == \"Collection after 48 hours of admission\") |>\n",
        "    # filtering for dates of interest\n",
        "    mutate(SAMPLE_COLLECTED_DT = as.Date(SAMPLE_COLLECTED_DT, format = \"%Y-%m-%d\")) |>\n",
        "    #filter(SAMPLE_COLLECTED_DT >= \"2020-04-01\" & SAMPLE_COLLECTED_DT <= \"2020-04-30\") |> # Ec spike april 2020\n",
        "    filter(SAMPLE_COLLECTED_DT >= \"2021-02-01\" & SAMPLE_COLLECTED_DT <= \"2021-02-28\") |> # Ec spike feb 2021\n",
        "    #filter(SAMPLE_COLLECTED_DT >= \"2021-01-01\" & SAMPLE_COLLECTED_DT <= \"2021-02-28\") |> # Kpn spike jan-feb 2021\n",
        "    select(SUBJECT,\n",
        "           AGE_AT_ADMISSION,\n",
        "           sex=GENDER_DESC,\n",
        "           ETHNICITY_DESC) |>\n",
        "    mutate(sex = str_to_title(sex),\n",
        "           AGE_AT_ADMISSION = as.numeric(AGE_AT_ADMISSION)) |>\n",
        "    distinct() |>\n",
        "    mutate(\n",
        "           age_band = cut(\n",
        "            AGE_AT_ADMISSION,\n",
        "            breaks = c(-Inf, 1, 5, 9, 17, 25, 40, 65, 80, Inf),\n",
        "            lables = c(\"leq1\", \"2-5\", \" 6-9\", \"10-17\", \"18-25\", \"26-20\",\"41-65\", \"65-80\", \"80+\"),\n",
        "            right=TRUE\n",
        "           )\n",
        "    ) |>\n",
        "    count(age_band, sex) |>\n",
        "    pivot_wider(names_from = sex, values_from=n, values_fill = 0) |>\n",
        "    mutate(\n",
        "        M_pct = round(Male/sum(Male)*100, 1),\n",
        "        F_pct = round(Female/sum(Female)*100, 1),\n",
        "        Total = Male+Female,\n",
        "        Total_pct = round(Total/sum(Total)*100, 1)\n",
        "    )\n",
        "\n",
        "bind_rows(table, \n",
        "            table |>\n",
        "            summarise(across(-age_band, sum)) |>\n",
        "            mutate(age_band = \"Overall\")) |>\n",
        "            kable(align=\"lrrrrrr\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "nteract": {
          "transient": {
            "deleting": false
          }
        }
      },
      "source": [
        "## what accounts for the greater difference between HO versus CO isolates in Kpn & Other Enterobacteriaceae for all isolates compared to blood isolates only? culture type/bacteria\n",
        "### looks like Enterobacter spp. are primarily responsible"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1753098201973
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "micro_cf |>\n",
        "    # filtering for blood cultures only\n",
        "    filter(str_detect(ORDER_NAME,\n",
        "                      \"urine\"\n",
        "                      #\"sputum\"\n",
        "                      ),\n",
        "           str_detect(SENSITIVITY,\n",
        "                      \"enterobacter\"\n",
        "                      #\"klebsiella pneumoniae\"\n",
        "                      )\n",
        "           ) |>\n",
        "    group_by(SENSITIVITY) |>\n",
        "    tally() |>\n",
        "    arrange(desc(n)) |>\n",
        "    kable()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "gather": {
          "logged": 1751984135852
        },
        "vscode": {
          "languageId": "r"
        }
      },
      "outputs": [],
      "source": [
        "all_data |>\n",
        " # filtering non-Enterobacteriaceae\n",
        "  filter(ORGANISM_OR_BUG != \"Other, including Gram +ves\") |>\n",
        "  # selecting columns of interest\n",
        "  select(SUBJECT,\n",
        "         SPELL_IDENTIFIER,\n",
        "         EPISODE_IDENTIFIER,\n",
        "         SAMPLE_COLLECTED_DT,\n",
        "         WITHIN_SPELL,\n",
        "         AFTER_48HRS,\n",
        "         ORGANISM_OR_BUG) |>\n",
        "  # removing duplicates\n",
        "  distinct() |>\n",
        "  # creating month column\n",
        "  mutate(MONTH=lubridate::floor_date(SAMPLE_COLLECTED_DT, \"month\"),\n",
        "         # defining hospital onset infections\n",
        "         HO=if_else(\n",
        "           !is.na(WITHIN_SPELL) &\n",
        "             WITHIN_SPELL == TRUE &\n",
        "             !is.na(AFTER_48HRS) &\n",
        "             AFTER_48HRS == \"Collection after 48 hours of admission\", \"Hospital Onset\", \n",
        "           # defining community onset infections\n",
        "           if_else(\n",
        "             !is.na(WITHIN_SPELL) &\n",
        "               !is.na(AFTER_48HRS) &\n",
        "               AFTER_48HRS == \"Collection within 48 hours of admission\", \"Community Onset\",\n",
        "            # else\n",
        "            \"Undefined\"))) |>\n",
        "   # filtering incomplete end month\n",
        "  filter(MONTH < end_date) |>\n",
        "  # counting total bugs per month for each bug\n",
        "  group_by(\n",
        "    ORGANISM_OR_BUG,\n",
        "    HO,\n",
        "    MONTH\n",
        "  ) |>\n",
        "  tally()"
      ]
    }
  ],
  "metadata": {
    "kernel_info": {
      "name": "ir"
    },
    "kernelspec": {
      "display_name": "R",
      "language": "R",
      "name": "ir"
    },
    "language_info": {
      "codemirror_mode": "r",
      "file_extension": ".r",
      "mimetype": "text/x-r-source",
      "name": "R",
      "pygments_lexer": "r",
      "version": "4.5.0"
    },
    "microsoft": {
      "host": {
        "AzureML": {
          "notebookHasBeenCompleted": true
        }
      },
      "ms_spell_check": {
        "ms_spell_check_language": "en"
      }
    },
    "nteract": {
      "version": "nteract-front-end@1.0.0"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}
