knitr::opts_chunk$set(echo = TRUE)
library(readr)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(tidyr)
library(lubridate)
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
library(ggplot2)
library(openxlsx)
library(readxl)
# Read the region 1 xlsx file
# The 'skip = 2' argument is used to skip the first two rows which contains header information
Region_1_data <- read_excel("C:/Users/RTank/Desktop/Senior Scientist Task/Region_1_data.xlsx", skip = 2)
View(Region_1_data)
# Read the region 2 CSV file
Region_2_data <- read.csv("C:/Users/RTank/Desktop/Senior Scientist Task/Region_2_data.csv")
View(Region_2_data)
This helps in understanding the data and planning for any necessary data transformation or cleaning.
# visually inspect the class and structure of each column
class_list <- lapply(Region_1_data, class)
print(class_list)
## $`Anonymised patient ID`
## [1] "character"
##
## $`Sample date`
## [1] "POSIXct" "POSIXt"
##
## $`Receipt date at PHL`
## [1] "POSIXct" "POSIXt"
##
## $`PHL laboratory report date`
## [1] "POSIXct" "POSIXt"
##
## $`Sample type`
## [1] "character"
##
## $`Sending/feeder laboratory name`
## [1] "character"
##
## $`Pathogen X result`
## [1] "character"
##
## $`Inpatient/outpatient indicator`
## [1] "character"
##
## $`Primary diagnostic`
## [1] "character"
##
## $`Referral sample`
## [1] "character"
##
## $`Region Code`
## [1] "character"
structure_list <- lapply(Region_1_data, str)
## chr [1:21213] "26880" "84964" "103829" "111364" "153338" "165084" "175664" ...
## POSIXct[1:21213], format: "2017-12-29" "2017-12-21" "2016-04-10" "2016-04-10" "2017-12-04" ...
## POSIXct[1:21213], format: "2017-12-30" "2017-12-22" "2016-04-12" "2016-04-11" "2017-12-05" ...
## POSIXct[1:21213], format: "2017-12-31" "2017-12-22" "2016-04-13" "2016-04-11" "2017-12-05" ...
## chr [1:21213] "Faeces" "Faeces" "Vomit" "Vomit" "Faeces" "Faeces" "Vomit" ...
## chr [1:21213] "NHS Trust C" "NHS Trust L" "NHS Trust N" "NHS Trust N" ...
## chr [1:21213] "Positive" "Positive" "Positive" "Positive" "Positive" ...
## chr [1:21213] "GP" "Inpatient" "Inpatient" "Outpatient" "Inpatient" ...
## chr [1:21213] "Yes" "Yes" "Yes" "Yes" "Yes" "Yes" "Yes" "Yes" "Yes" "Yes" ...
## chr [1:21213] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA ...
## chr [1:21213] "E12000002" "E12000002" "E12000002" "E12000002" "E12000002" ...
# view the first few instances of each column and view instances in categorical columns
head(Region_1_data)
## # A tibble: 6 x 11
## `Anonymised patient ID` `Sample date` `Receipt date at PHL`
## <chr> <dttm> <dttm>
## 1 26880 2017-12-29 00:00:00 2017-12-30 00:00:00
## 2 84964 2017-12-21 00:00:00 2017-12-22 00:00:00
## 3 103829 2016-04-10 00:00:00 2016-04-12 00:00:00
## 4 111364 2016-04-10 00:00:00 2016-04-11 00:00:00
## 5 153338 2017-12-04 00:00:00 2017-12-05 00:00:00
## 6 165084 2019-01-19 00:00:00 2019-01-20 00:00:00
## # i 8 more variables: `PHL laboratory report date` <dttm>, `Sample type` <chr>,
## # `Sending/feeder laboratory name` <chr>, `Pathogen X result` <chr>,
## # `Inpatient/outpatient indicator` <chr>, `Primary diagnostic` <chr>,
## # `Referral sample` <chr>, `Region Code` <chr>
# View the counts for different categories within factor columns to identify outliers using table
table(Region_1_data$`Pathogen X result`)
##
## Negative Positive
## 18435 2778
It is notable that NHE Trust F is missing from Sending/feeder laboratory name
# Cleaning 'Anonymised patient ID' column
# Use sub() to remove everything after '|' in Anonymised patient ID
Region_1_data$`Anonymised patient ID` <- sub("\\|.*", "" , Region_1_data$`Anonymised patient ID`)
# Convert Anonymised patient ID to numeric
Region_1_data$`Anonymised patient ID` <- as.numeric(Region_1_data$`Anonymised patient ID`)
# Dataset now needs to be deduplicated and the first positive case should be selected
# Duplication check code
# Checks whether there are duplicates in the column Anonymised patient ID
# TRUE=No duplicates, FALSE=duplicates
length(unique(Region_1_data$`Anonymised patient ID`)) == nrow(Region_1_data)
## [1] FALSE
#Creates a data frame with a list of Anonymised patient IDs and the number of times they occurred.
n_occur <- data.frame(table(Region_1_data$`Anonymised patient ID`))
# Creates a new dataframe of Anonymised patient IDs that occurred >1 and the frequency of occurrences
n_occur_count <- n_occur[n_occur$Freq > 1,]
table(n_occur_count$Freq)
##
## 2
## 491
From the duplication check code we can see there are 21 individuals duplicated once (counted twice) in the total 2778 positive cases. We should end up with 2757 (2778 - 21 = 2757) cases of pathogen x in region 1 if we filter for both positive cases only and selecting only the first instance for each case
# Deduplicating and selecting the first positive case
Region_1_data_deduplicated <- Region_1_data %>%
arrange(`Anonymised patient ID`, `Sample date`) %>%
filter(`Pathogen X result` == "Positive") %>%
distinct(`Anonymised patient ID`, .keep_all = TRUE)
# Checking for duplicates
# TRUE=No duplicates, FALSE=duplicates
length(unique(Region_1_data_deduplicated$`Anonymised patient ID`)) == nrow(Region_1_data_deduplicated)
## [1] TRUE
table(Region_1_data_deduplicated$`Pathogen X result`)
##
## Positive
## 2757
# visually inspect the class and structure of each column
class_list <- lapply(Region_2_data, class)
print(class_list)
## $Ano_pt_ID
## [1] "integer"
##
## $Spec_type
## [1] "character"
##
## $Spec_date
## [1] "character"
##
## $Receipt_date
## [1] "character"
##
## $Report_date
## [1] "character"
##
## $Result
## [1] "character"
##
## $Inpt_outpt_indicator
## [1] "character"
##
## $Requesting_organisation
## [1] "character"
##
## $Setting
## [1] "character"
##
## $region_code
## [1] "character"
structure_list <- lapply(Region_2_data, str)
## int [1:1916] 1238 1239 1240 1319 1317 1318 1274 1320 1324 1326 ...
## chr [1:1916] "FAE" "FAE" "FAE" "FAE" "FAE" "FAE" "FAE" "FAE" "FAE" "FAE" ...
## chr [1:1916] "2019-08-27" "2019-08-28" "2019-08-29" "2019-11-10" ...
## chr [1:1916] "2019-08-29" "2019-08-29" "2019-08-30" "2019-11-13" ...
## chr [1:1916] "2019-08-30" "2019-08-30" "2019-08-30" "2019-11-15" ...
## chr [1:1916] "POSITIVE" "POSITIVE" "POSITIVE" "POSITIVE" "POSITIVE" ...
## chr [1:1916] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA ...
## chr [1:1916] "EH" "EH" "EH" "EH" "EH" "EH" "EH" "EH" "EH" "EH" "EH" "EH" ...
## chr [1:1916] "EH" "EH" "EH" "EH" "EH" "EH" "EH" "EH" "EH" "EH" "EH" "EH" ...
## chr [1:1916] "E12000004" "E12000004" "E12000004" "E12000004" "E12000004" ...
# view the first few instances of each column
head(Region_2_data)
## Ano_pt_ID Spec_type Spec_date Receipt_date Report_date Result
## 1 1238 FAE 2019-08-27 2019-08-29 2019-08-30 POSITIVE
## 2 1239 FAE 2019-08-28 2019-08-29 2019-08-30 POSITIVE
## 3 1240 FAE 2019-08-29 2019-08-30 2019-08-30 POSITIVE
## 4 1319 FAE 2019-11-10 2019-11-13 2019-11-15 POSITIVE
## 5 1317 FAE 2019-11-11 2019-11-13 2019-11-15 POSITIVE
## 6 1318 FAE 2019-11-12 2019-11-13 2019-11-15 POSITIVE
## Inpt_outpt_indicator Requesting_organisation Setting region_code
## 1 <NA> EH EH E12000004
## 2 <NA> EH EH E12000004
## 3 <NA> EH EH E12000004
## 4 <NA> EH EH E12000004
## 5 <NA> EH EH E12000004
## 6 <NA> EH EH E12000004
# Convert columns to appropriate formats
Region_2_data$Ano_pt_ID <- as.numeric(Region_2_data$Ano_pt_ID)
Region_2_data$Spec_date <- as.POSIXct(Region_2_data$Spec_date)
Region_2_data$Receipt_date <- as.POSIXct(Region_2_data$Receipt_date)
Region_2_data$Report_date <- as.POSIXct(Region_2_data$Report_date)
Region_2_data <- Region_2_data %>%
mutate(Spec_type = case_when(
Spec_type == "FAE" ~ "Faeces",
Spec_type == "VOM" ~ "Vomit" ))
table(Region_2_data$Spec_type)
##
## Faeces Vomit
## 1737 177
# It is notable that two cases have missing data for sample type which will remain in the dataframe with an NA value for sample type.
# Duplication check code
# TRUE=No duplicates, FALSE=duplicates
length(unique(Region_2_data$Ano_pt_ID)) == nrow(Region_2_data)
## [1] FALSE
#Creates a data frame with a list of Anonymised patient IDs and the number of times they occurred.
n_occur <- data.frame(table(Region_2_data$Ano_pt_ID))
# Creates a new dataframe of Anonymised patient IDs that occurred >1 and the frequency of occurrences
n_occur_count <- n_occur[n_occur$Freq > 1,]
table(n_occur_count$Freq)
##
## 2
## 636
Duplication checks show that out of 964 positive cases, 318 individuals have been duplicated once (counted twice) filtering for the first positive instance should result in 646 individual cases (964 - 318 = 646) of pathogen x in region 2
# Deduplicating and selecting the first positive case
Region_2_data_deduplicated <- Region_2_data %>%
arrange(Ano_pt_ID, `Spec_date`) %>%
filter(Result == "POSITIVE") %>%
distinct(Ano_pt_ID, .keep_all = TRUE)
# TRUE=No duplicates, FALSE=duplicates
length(unique(Region_2_data_deduplicated$Ano_pt_ID)) == nrow(Region_2_data_deduplicated)
## [1] TRUE
table(Region_2_data_deduplicated$Result)
##
## POSITIVE
## 646
# Standardizing column names and merging datasets
# Converting 'Pathogen X result' to lowercase in both datasets for case consistency in merging
Region_1_data_deduplicated$`Pathogen X result` <- tolower(Region_1_data_deduplicated$`Pathogen X result`)
Region_2_data_deduplicated$Result <- tolower(Region_2_data_deduplicated$Result)
# Renaming relevant columns in Region_2_data_deduplicated to match those in Region_1_data_deduplicated
Region_2_data_deduplicated <- rename(Region_2_data_deduplicated,
`Anonymised patient ID` = Ano_pt_ID,
`Sample date` = Spec_date, `Sample type` = Spec_type,
`Receipt date at PHL` = Receipt_date,
`PHL laboratory report date` = Report_date,
`Pathogen X result` = Result,
`Region Code` = region_code)
# Merging the two datasets into one combined dataset.
# This combined dataset will be used for further analysis.
combined_data <- bind_rows(Region_1_data_deduplicated, Region_2_data_deduplicated)
# TRUE=No duplicates, FALSE=duplicates
length(unique(combined_data$`Anonymised patient ID`)) == nrow(combined_data)
## [1] TRUE
To calculate the infection rates per 100,000 population, I used population estimates from the 2021 Office for National Statistics (ONS) England Census, matching the dataset’s geographical codes with those in the Census. I utilised the Census website’s “Build Custom Area Profile” tool for accurate regional population estimates. This tool aggregates data from small areas and rounds estimates to the nearest 100 people. These estimates assumed a total population of 56,490,000 in England in 2021. Notably, the epidemiological data covered 2016 to 2020, whereas the ONS Census data is from 2021. I carried out the present analysis with the assumption that the population characteristics during pathogen X’s study period didn’t significantly differ from the 2021 data. This assumption may introduce inaccuracies in the results. Despite potential limitations due to this time discrepancy, the 2021 Census offers up-to-date and detailed population information, making it a reliable source for the present analysis.
The estimates for the present analysis are as follows:
Total population for geographical region 1 (E12000002) according to 2021 census data was 7,417,400. Total population for geographical region 2 (E12000004) according to 2021 census data was 4,880,100.
Source: Office for National Statistics - Census 2021
# Preparing the combined dataset for weekly analysis by year.
# filtering for positive cases, extracting year and week from the 'PHL laboratory report date',
# and summarizing the data to get the count of positive cases per week per year.
weekly_data_by_year <- combined_data %>%
filter(`Pathogen X result` == "positive") %>%
mutate(Year = year(`PHL laboratory report date`),
Week = week(`PHL laboratory report date`)) %>%
group_by(Year, Week) %>%
summarise(Positive_Cases = n(), .groups = 'drop')
# Exporting the weekly_data_by_year dataset to a CSV file
write_csv(weekly_data_by_year, "C:/Users/RTank/Desktop/Senior Scientist Task/weekly_data_by_year.csv")
# Plotting the weekly epidemiological curve with lines for each year
ggplot(weekly_data_by_year, aes(x = Week, y = Positive_Cases, group = Year, color = as.factor(Year))) +
geom_line() +
labs(title = "Weekly Epidemiological Curve by Year",
x = "Week Number",
y = "Number of Positive Cases",
color = "Year") +
theme_minimal() +
scale_color_brewer(palette = "Set1")
# First, the population data is defined for each region.
# The next steps involve calculating the annual positive infection counts for each region,
# joining it with the population data, and finally calculating the infection rates per 100,000 population.
# This metric is important for understanding the relative impact of the pathogen in different regions.
# Population data
population_data <- data.frame(
Region_Code = c("E12000002", "E12000004"),
Population = c(7417400, 4880100)
)
# Calculate annual positive infection counts for each region
annual_infections <- combined_data %>%
filter(`Pathogen X result` == "positive") %>%
mutate(Year = year(`PHL laboratory report date`)) %>%
group_by(Year, `Region Code`) %>%
summarise(Positive_Cases = n(), .groups = 'drop')
# Join with population data
annual_infections <- left_join(annual_infections, population_data, by = c("Region Code" = "Region_Code"))
write_csv(annual_infections, "C:/Users/RTank/Desktop/Senior Scientist Task/annual_infection_rates_by_region.csv")
# Calculate infection rates per 100,000 population
annual_infections$Infection_Rate <- (annual_infections$Positive_Cases / annual_infections$Population) * 100000
# Plotting infection rates
ggplot(annual_infections, aes(x = Year, y = Infection_Rate, fill = `Region Code`)) +
geom_bar(stat = "identity", position = position_dodge()) +
labs(title = "Infection Rates per 100,000 Population by Year and Region",
x = "Year",
y = "Infection Rate per 100,000 Population",
fill = "Region Code") +
theme_minimal()
# Calculate delays
combined_data$Delay <- as.numeric(difftime(combined_data$`Receipt date at PHL`, combined_data$`Sample date`, units = "days"))
# Group by sample type and region, then summarize
delay_summary <- combined_data %>%
group_by(`Sample type`, `Region Code`) %>%
summarise(Mean_Delay = mean(Delay, na.rm = TRUE),
Median_Delay = median(Delay, na.rm = TRUE),
Min_Delay = min(Delay, na.rm = TRUE),
Max_Delay = max(Delay, na.rm = TRUE),
.groups = 'drop')
write_csv(delay_summary, "C:/Users/RTank/Desktop/Senior Scientist Task/delay_summary.csv")
# Visualizing delays
ggplot(delay_summary, aes(x = `Sample type`, y = Mean_Delay, fill = `Region Code`)) +
geom_bar(stat = "identity", position = position_dodge()) +
labs(title = "Average Delay by Sample Type and Region",
x = "Sample Type",
y = "Average Delay (days)",
fill = "Region Code") +
theme_minimal()
# Visualizing delays with a box and whisker plot to further examine the high value for faeces for region E12000004
ggplot(combined_data, aes(x = `Sample type`, y = Delay, fill = `Region Code`)) +
geom_boxplot(outlier.shape = NA) + # Add boxplot, hide outliers for cleaner look
geom_jitter(width = 0.2, size = 1, alpha = 0.4) + # Add jitter to show individual data points
labs(title = "Delay Distribution by Sample Type and Region",
x = "Sample Type",
y = "Delay (days)",
fill = "Region Code") +
theme_minimal()
# Visualising as a box and whisker plot illustrates the skew in the data due to outliers: two cases with delays exceeding 300 days
# Visualizing delays with enhanced signposting for more accurate interpretation of the data
ggplot(delay_summary, aes(x = `Sample type`, y = Mean_Delay, fill = `Region Code`)) +
geom_bar(stat = "identity", position = position_dodge()) +
geom_text(aes(label = round(Mean_Delay, 1)),
position = position_dodge(width = 0.9),
vjust = -0.25,
color = "black",
size = 3.5) + # Add text labels to the bars
labs(title = "Average Delay by Sample Type and Region",
x = "Sample Type",
y = "Average Delay (days)",
fill = "Region Code") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) # Adjust x-axis labels for better readability