Breakdown of the Data - Dive:
Set-up:
# Load the libs
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.2.3
##
## 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(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✔ ggplot2 3.3.6 ✔ purrr 0.3.4
## ✔ tibble 3.2.1 ✔ stringr 1.4.0
## ✔ tidyr 1.2.0 ✔ forcats 0.5.1
## ✔ readr 2.1.2
## Warning: package 'tibble' was built under R version 4.2.3
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
library(stats) # For Geometric and Binomail Distrubtion anomaly tests.
library(ggplot2) # For visuals, but I didn't have time for visuals. So, instead it is used to reformat my findings into a data.frame.
# Re-instance the COVID data set:
COVID = read_delim("../data/COVID_country.csv",delim = ",")
## New names:
## • `` -> `...11`
## Rows: 6208 Columns: 11
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (5): country, iso3, sex, age_group, type
## dbl (5): year, pop, expected.mean, acm.mean, excess.mean*
## lgl (1): ...11
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Alias the COVID data set name :D
data <- COVID
summary(data)
## country iso3 year sex
## Length:6208 Length:6208 Min. :2020 Length:6208
## Class :character Class :character 1st Qu.:2020 Class :character
## Mode :character Mode :character Median :2020 Mode :character
## Mean :2020
## 3rd Qu.:2021
## Max. :2021
## age_group pop type expected.mean
## Length:6208 Min. : 0 Length:6208 Min. : 0.0
## Class :character 1st Qu.: 35177 Class :character 1st Qu.: 370.8
## Mode :character Median : 267600 Mode :character Median : 2438.0
## Mean : 2520267 Mean : 17998.0
## 3rd Qu.: 1194828 3rd Qu.: 9056.5
## Max. :324033981 Max. :1578937.0
## acm.mean excess.mean* ...11
## Min. : 0 Min. :-100092.0 Mode:logical
## 1st Qu.: 411 1st Qu.: 0.0 NA's:6208
## Median : 2720 Median : 84.0
## Mean : 20403 Mean : 2394.2
## 3rd Qu.: 10440 3rd Qu.: 799.2
## Max. :1733563 Max. : 588931.0
# Create a new attribute, as my data set does not have 6 numeric columns, which actually surprised me, LOL. But, I realized that some 'numeric' cols I thought,
# Append to the data frame
data$numeric_ages <- as.numeric(factor(data$age_group))
# check it was added
head(data)
## # A tibble: 6 × 12
## country iso3 year sex age_group pop type expected.mean acm.mean
## <chr> <chr> <dbl> <chr> <chr> <dbl> <chr> <dbl> <dbl>
## 1 Afghanistan AFG 2020 Female 0-24 12485568 pred… 49084 49103
## 2 Afghanistan AFG 2020 Female 25-34 2734917 pred… 6453 6691
## 3 Afghanistan AFG 2020 Female 35-44 1684126 pred… 6118 6977
## 4 Afghanistan AFG 2020 Female 45-54 1141134 pred… 7712 9330
## 5 Afghanistan AFG 2020 Female 55-64 699319 pred… 10062 12458
## 6 Afghanistan AFG 2020 Female 65-74 379159 pred… 13955 17144
## # ℹ 3 more variables: `excess.mean*` <dbl>, ...11 <lgl>, numeric_ages <dbl>
I’m going to do it in an elegant manner. Instead of simply copying and pasting the same code, I will construct an algorithm that will compute 6 data frames (sub_dfs) from the COVID data set.
Procedure:
# Local Var time :D
# set number of samples! This is also nice because you can download the Rmd file and change it to your liking!
num_dfs <- 6 # sets the number of data frames to be iterated through (aka; created).
sub_per <- 0.5 # Fraction of data to include in each sub df. (sub_per ===> subset_percent)
sub_dfs <- list() # list to contain the subset data frames. (covid_sub_dfs ==> COVID [data], sub samples [or, subsets], data frames)
set up the data frames:
# Algo:
for (i in 1:num_dfs){
# Randomly select rows WITH replacement:
df_indices <- sample(1:nrow(data), size = round(nrow(data) * sub_per), replace = TRUE)
# Grab only numeric columns that are either discrete or continuous.
num_columns <- sample(names(data)[sapply(data, is.numeric)], size = 6, replace = FALSE)
# combine the selected columns.
columns <- num_columns
# Create the subset df
sub_df <- data[df_indices, columns]
# store the sub_dfs in the list:
sub_dfs[[paste0("df_", i)]] <- sub_df
}
Let’s remind our feels of what we want to answer:
In order to answer these questions, I need to perform normality tests and identify anomalies:
R-Script:
# Find anomalies (outliers) using probability distribution:
# Here is the breakdown of my function `find_anomalies`:
# It takes two arguments:
# `current_col` : a numeric vector of data.
# `dis_type` : a string indicating the probability distribution to use for anomaly detection.
find_anomalies <- function(current_col, dis_type) {
if (dis_type == "binomial") {
# Parameters for the binomial distribution
size <- 10
prob <- 0.5
# I'm creating data because it serves as a vital reference point for anomaly identification and hypothesis testing because it is based on a specified probability distribution.A hypothesis, for example, could be, but instead we did anomaly detection:
# H0: The population size of countries across different regions within the data set is the same.
# H1: The population size of countries across different regions within the data set is not the same
# Overall, I was able to construct a baseline expectation for the data through this procedure. We can construct p-values by comparing the actual data to this reference, which represents the likelihood of observing data as extreme as what I have under the premise that the data follows the specified distribution. This allows me to quantify the degree of anomaly for each data point and establish a significant threshold for detecting anomalies (0.05). This, in essence, provides a statistical framework for determining whether the observed data exhibits patterns compatible with the anticipated distribution and aids in the identification of anomalies. By identifying data points with very low p-values, indicating a significant deviation from the predicted trend.
# Generate random values from the binomial distribution
rand_vals <- rbinom(length(current_col), size, prob)
# Calculate p-values by comparing the observed data to the generated data
p_values <- lapply(rand_vals, function(rand_val) {
pbinom(sum(current_col >= rand_val), length(current_col), prob)
})
} else if (dis_type == "geometric") {
# Parameter for the geometric distribution (you can adjust as needed)
prob <- 0.2
# Generate random values from the geometric distribution
rand_vals <- rgeom(length(current_col), prob)
# Calculate p-values by comparing the observed data to the generated data
p_values <- lapply(rand_vals, function(rand_val) {
pgeom(sum(current_col >= rand_val), prob)
})
} else {
# if the second argument doesn't match one of the given distirbution types stop the algo and arise an error.
stop("Invalid distribution type")
}
# Define anomaly threshold (significance level of 0.05)
anomaly_threshold <- 0.05
# Detect anomalies based on the p-values
anomalies <- lapply(p_values, function(p_value){
return(p_value < anomaly_threshold)
})
return(anomalies)
}
# Init: empty list for my results:
results <- list()
# Remember, num_dfs === '6', or whatever the user plugs in.
# Loop through each sub_df
for(i in 1:num_dfs){
sub_df <- sub_dfs[[paste0("df_", i)]]
# Calculate mean and StDev
numeric_cols <- sub_df[, sapply(sub_df, is.numeric)]
mean_value <- colMeans(numeric_cols, na.rm = TRUE)
std_dev <- apply(numeric_cols, 2, sd, na.rm = TRUE)
# Detect anomalies based on the binomial distribution
binomial <- find_anomalies(numeric_cols, "binomial")
# Detect anomalies based on the geometric distribution
geometric <- find_anomalies(numeric_cols, "geometric")
# Store the results in a list:
result <- data.frame(
MeanValues = mean_value,
StandardDeviations = std_dev,
BinomialAnomalies = binomial,
GeometricAnomalies = geometric
)
# Print the results in tabular format
cat("Results for the Attribute: ", names(numeric_cols[i]), "In sub_df: ", i, "\n")
cat("\n")
print(result)
cat("\n")
}
## Results for the Attribute: expected.mean In sub_df: 1
##
## MeanValues StandardDeviations BinomialAnomalies.FALSE
## expected.mean 1.658667e+04 7.247005e+04 FALSE
## numeric_ages 4.484214e+00 2.254171e+00 FALSE
## excess.mean* 2.081489e+03 1.293879e+04 FALSE
## pop 2.209138e+06 1.070235e+07 FALSE
## acm.mean 1.867467e+04 7.897833e+04 FALSE
## year 2.020502e+03 5.000780e-01 FALSE
## BinomialAnomalies.FALSE.1 BinomialAnomalies.FALSE.2
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## acm.mean FALSE FALSE
## year FALSE FALSE
## BinomialAnomalies.FALSE.3 BinomialAnomalies.FALSE.4
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## acm.mean FALSE FALSE
## year FALSE FALSE
## BinomialAnomalies.FALSE.5 GeometricAnomalies.FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## acm.mean FALSE FALSE
## year FALSE FALSE
## GeometricAnomalies.FALSE.1 GeometricAnomalies.FALSE.2
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## acm.mean FALSE FALSE
## year FALSE FALSE
## GeometricAnomalies.FALSE.3 GeometricAnomalies.FALSE.4
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## acm.mean FALSE FALSE
## year FALSE FALSE
## GeometricAnomalies.FALSE.5
## expected.mean FALSE
## numeric_ages FALSE
## excess.mean* FALSE
## pop FALSE
## acm.mean FALSE
## year FALSE
##
## Results for the Attribute: acm.mean In sub_df: 2
##
## MeanValues StandardDeviations BinomialAnomalies.FALSE
## excess.mean* 2.128718e+03 1.541135e+04 FALSE
## acm.mean 1.903681e+04 9.113765e+04 FALSE
## year 2.020509e+03 4.999992e-01 FALSE
## numeric_ages 4.499034e+00 2.320862e+00 FALSE
## expected.mean 1.690107e+04 8.435465e+04 FALSE
## pop 2.167589e+06 1.015899e+07 FALSE
## BinomialAnomalies.FALSE.1 BinomialAnomalies.FALSE.2
## excess.mean* FALSE FALSE
## acm.mean FALSE FALSE
## year FALSE FALSE
## numeric_ages FALSE FALSE
## expected.mean FALSE FALSE
## pop FALSE FALSE
## BinomialAnomalies.FALSE.3 BinomialAnomalies.FALSE.4
## excess.mean* FALSE FALSE
## acm.mean FALSE FALSE
## year FALSE FALSE
## numeric_ages FALSE FALSE
## expected.mean FALSE FALSE
## pop FALSE FALSE
## BinomialAnomalies.FALSE.5 GeometricAnomalies.FALSE
## excess.mean* FALSE FALSE
## acm.mean FALSE FALSE
## year FALSE FALSE
## numeric_ages FALSE FALSE
## expected.mean FALSE FALSE
## pop FALSE FALSE
## GeometricAnomalies.FALSE.1 GeometricAnomalies.FALSE.2
## excess.mean* FALSE FALSE
## acm.mean FALSE FALSE
## year FALSE FALSE
## numeric_ages FALSE FALSE
## expected.mean FALSE FALSE
## pop FALSE FALSE
## GeometricAnomalies.FALSE.3 GeometricAnomalies.FALSE.4
## excess.mean* FALSE FALSE
## acm.mean FALSE FALSE
## year FALSE FALSE
## numeric_ages FALSE FALSE
## expected.mean FALSE FALSE
## pop FALSE FALSE
## GeometricAnomalies.FALSE.5
## excess.mean* FALSE
## acm.mean FALSE
## year FALSE
## numeric_ages FALSE
## expected.mean FALSE
## pop FALSE
##
## Results for the Attribute: acm.mean In sub_df: 3
##
## MeanValues StandardDeviations BinomialAnomalies.FALSE
## expected.mean 1.796706e+04 8.062899e+04 FALSE
## numeric_ages 4.506121e+00 2.286581e+00 FALSE
## acm.mean 2.069423e+04 9.343653e+04 FALSE
## excess.mean* 2.717085e+03 2.113677e+04 FALSE
## year 2.020493e+03 5.000303e-01 FALSE
## pop 2.580104e+06 1.260568e+07 FALSE
## BinomialAnomalies.FALSE.1 BinomialAnomalies.FALSE.2
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## acm.mean FALSE FALSE
## excess.mean* FALSE FALSE
## year FALSE FALSE
## pop FALSE FALSE
## BinomialAnomalies.FALSE.3 BinomialAnomalies.FALSE.4
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## acm.mean FALSE FALSE
## excess.mean* FALSE FALSE
## year FALSE FALSE
## pop FALSE FALSE
## BinomialAnomalies.FALSE.5 GeometricAnomalies.FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## acm.mean FALSE FALSE
## excess.mean* FALSE FALSE
## year FALSE FALSE
## pop FALSE FALSE
## GeometricAnomalies.FALSE.1 GeometricAnomalies.FALSE.2
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## acm.mean FALSE FALSE
## excess.mean* FALSE FALSE
## year FALSE FALSE
## pop FALSE FALSE
## GeometricAnomalies.FALSE.3 GeometricAnomalies.FALSE.4
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## acm.mean FALSE FALSE
## excess.mean* FALSE FALSE
## year FALSE FALSE
## pop FALSE FALSE
## GeometricAnomalies.FALSE.5
## expected.mean FALSE
## numeric_ages FALSE
## acm.mean FALSE
## excess.mean* FALSE
## year FALSE
## pop FALSE
##
## Results for the Attribute: excess.mean* In sub_df: 4
##
## MeanValues StandardDeviations BinomialAnomalies.FALSE
## numeric_ages 4.434278e+00 2.298859e+00 FALSE
## acm.mean 1.821360e+04 8.715976e+04 FALSE
## expected.mean 1.604088e+04 7.745743e+04 FALSE
## excess.mean* 2.157389e+03 1.749548e+04 FALSE
## pop 2.055572e+06 8.182486e+06 FALSE
## year 2.020504e+03 5.000656e-01 FALSE
## BinomialAnomalies.FALSE.1 BinomialAnomalies.FALSE.2
## numeric_ages FALSE FALSE
## acm.mean FALSE FALSE
## expected.mean FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## year FALSE FALSE
## BinomialAnomalies.FALSE.3 BinomialAnomalies.FALSE.4
## numeric_ages FALSE FALSE
## acm.mean FALSE FALSE
## expected.mean FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## year FALSE FALSE
## BinomialAnomalies.FALSE.5 GeometricAnomalies.FALSE
## numeric_ages FALSE FALSE
## acm.mean FALSE FALSE
## expected.mean FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## year FALSE FALSE
## GeometricAnomalies.FALSE.1 GeometricAnomalies.FALSE.2
## numeric_ages FALSE FALSE
## acm.mean FALSE FALSE
## expected.mean FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## year FALSE FALSE
## GeometricAnomalies.FALSE.3 GeometricAnomalies.FALSE.4
## numeric_ages FALSE FALSE
## acm.mean FALSE FALSE
## expected.mean FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## year FALSE FALSE
## GeometricAnomalies.FALSE.5
## numeric_ages FALSE
## acm.mean FALSE
## expected.mean FALSE
## excess.mean* FALSE
## pop FALSE
## year FALSE
##
## Results for the Attribute: expected.mean In sub_df: 5
##
## MeanValues StandardDeviations BinomialAnomalies.FALSE
## year 2.020510e+03 4.999808e-01 FALSE
## acm.mean 1.908238e+04 9.170348e+04 FALSE
## pop 2.256395e+06 9.751018e+06 FALSE
## excess.mean* 2.012124e+03 1.359516e+04 FALSE
## expected.mean 1.704492e+04 8.729876e+04 FALSE
## numeric_ages 4.586340e+00 2.265980e+00 FALSE
## BinomialAnomalies.FALSE.1 BinomialAnomalies.FALSE.2
## year FALSE FALSE
## acm.mean FALSE FALSE
## pop FALSE FALSE
## excess.mean* FALSE FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## BinomialAnomalies.FALSE.3 BinomialAnomalies.FALSE.4
## year FALSE FALSE
## acm.mean FALSE FALSE
## pop FALSE FALSE
## excess.mean* FALSE FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## BinomialAnomalies.FALSE.5 GeometricAnomalies.FALSE
## year FALSE FALSE
## acm.mean FALSE FALSE
## pop FALSE FALSE
## excess.mean* FALSE FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## GeometricAnomalies.FALSE.1 GeometricAnomalies.FALSE.2
## year FALSE FALSE
## acm.mean FALSE FALSE
## pop FALSE FALSE
## excess.mean* FALSE FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## GeometricAnomalies.FALSE.3 GeometricAnomalies.FALSE.4
## year FALSE FALSE
## acm.mean FALSE FALSE
## pop FALSE FALSE
## excess.mean* FALSE FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## GeometricAnomalies.FALSE.5
## year FALSE
## acm.mean FALSE
## pop FALSE
## excess.mean* FALSE
## expected.mean FALSE
## numeric_ages FALSE
##
## Results for the Attribute: pop In sub_df: 6
##
## MeanValues StandardDeviations BinomialAnomalies.FALSE
## acm.mean 2.171474e+04 9.592327e+04 FALSE
## year 2.020493e+03 5.000303e-01 FALSE
## expected.mean 1.920711e+04 8.839338e+04 FALSE
## numeric_ages 4.519330e+00 2.277327e+00 FALSE
## excess.mean* 2.498327e+03 1.626280e+04 FALSE
## pop 2.464040e+06 1.164529e+07 FALSE
## BinomialAnomalies.FALSE.1 BinomialAnomalies.FALSE.2
## acm.mean FALSE FALSE
## year FALSE FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## BinomialAnomalies.FALSE.3 BinomialAnomalies.FALSE.4
## acm.mean FALSE FALSE
## year FALSE FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## BinomialAnomalies.FALSE.5 GeometricAnomalies.FALSE
## acm.mean FALSE FALSE
## year FALSE FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## GeometricAnomalies.FALSE.1 GeometricAnomalies.FALSE.2
## acm.mean FALSE FALSE
## year FALSE FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## GeometricAnomalies.FALSE.3 GeometricAnomalies.FALSE.4
## acm.mean FALSE FALSE
## year FALSE FALSE
## expected.mean FALSE FALSE
## numeric_ages FALSE FALSE
## excess.mean* FALSE FALSE
## pop FALSE FALSE
## GeometricAnomalies.FALSE.5
## acm.mean FALSE
## year FALSE
## expected.mean FALSE
## numeric_ages FALSE
## excess.mean* FALSE
## pop FALSE
How different are the various sub_dfs?
As we can see, the outcomes for each data feature (attriute) varied across sub_dfs. The mean values and standard deviations can differ significantly between sub_dfs, reflecting the variability in the data. Consider the attribute “acm.mean” as an example.
‘acm.mean’ in sub_df 1:
‘acm.mean’ in sub_df 2:
‘acm.mean’ in sub_df 3:
‘acm.mean’ in sub_df 4:
‘acm.mean’ in sub_df 5:
‘acm.mean’ in sub_df 6:
Analyze the Differences among these sub_dfs for ‘acm.mean’:
While the mean values and standard deviations for the “acm.mean” attribute differ across all sub_dfs, neither the binomial distribution approach nor the geometric distribution method discovered any anomalies in any of the sub_dfs. This shows that in terms of anomaly identification using these methods, the ‘acm.mean’ looks to be consistent across sub_dfs. However, it is important to highlight that this conclusion applies only to ‘acm.mean’ and that we should evaluate other attributes to see if they reflect different patterns of anomalies and variances over all sub-samples.
If I have time before submission I will show other attributes, if not, I will try to answer this question in more detail in the next data dive
What would you have called an anomaly in one sub-sample that you wouldn’t in another?
Anomalies are often identified using a predetermined threshold or statistical criterion. Anomalies are found in this RMarkdown using both binomial and geometric distribution approaches. Because of variances in the data distribution (which was random owing to sampling with replacement), what is regarded an anomaly in one sub_df may not be considered an anomaly in another sub_df. Anomalies are found depending on how far the observed data deviates from randomly produced data from the binomial or geometric distributions. If the observed data differs significantly from the created data, it is marked as an anomaly. The ‘anomaly_threshold’ variable (0.05), which can be changed, determines the particular threshold for what is considered a substantial deviation.
Are there aspects of the data that are consistent among all sub-samples?
According to the results, there are no consistent anomalies for any of the properties across all sub_dfs. As a result, the anomalies revealed by binomial and geometric distribution approaches differ among sub_dfs and characteristics. This shows that the anomalies are data-dependent and may not follow the same pattern across all sub_dfs.
It is crucial to note, however, that the consistency or lack thereof in anomaly detection may vary based on the individual data set and data distribution among the attributes. Anomalies are typically unique to the data and the anomaly detection method employed. As a result, the findings may vary depending on the data set and attribute distribution.
Several lessons may be made from the data inquiry and analysis of the sub_dfs utilizing various anomaly detection methods (Binomail and Geometric) that alter how inferences about the data should be drawn in the future:
These are my top three suggestions for improving my analysis and overall data dive. I was at my sister’s wedding this weekend and had to oversee this assignment, so I didn’t have much time to devote to it. However, if given the opportunity, I would like to resubmit with a more in-depth examination and findings.
Some other suggestions would be:
Summary:
Drawing inferences from data requires prudence and examination of the specific context, attributes, and methodologies employed. Future analyses should consider data variability, anomaly detection tools, and the requirement for consistency checks and replication. Domain expertise and data visualization should also be used to inform findings interpretation to ensure a more comprehensive and accurate understanding of the data.