Skip to content

Search Broadly Epi

Run a t-test in R

T-tests are a fundamental statistical tool used in various fields, including public health, to compare the means of two groups. Essentially, a T-test helps determine whether the observed differences in data sets (such as rates of a disease, responses to a treatment, or other health indicators) are statistically significant or likely due to chance. This test is vital in research and data analysis, as it provides a scientific basis for drawing conclusions about populations based on sample data. Whether it's comparing the effectiveness of different treatments, understanding health outcomes across different demographics, or analyzing behavioral health interventions, T-tests offer a reliable method for making informed, evidence-based decisions in public health and beyond. Here, we'll take a look at how to run a T-Test in R.  

Background: Understanding T-Tests

Before we look at how to run T-Tests in R, it's worth understanding what we're actually doing. As mentioned above, a T-Test is at its core, a comparison between two groups to see if they are different from each other in a way that cannot be explained by simple chance.

Types of T-Tests

There are 4 main groups of T-Tests that one may need to choose from when testing a hypothesis. These are:

This is a very broad overview of each category, and we'll cover more in our Epi Explained series entry on T-Tests. For now, we'll focus on perhaps the broadest and most generally applicable T-Test for our tutorial, the 2 tailed T-Test. Let's get started.

Mathematical Underpinnings

In terms of the underlying math for T-Tests, it's not quite as easy as our previous topics of Odds Ratio and Relative Risk, and can even seem a bit intimidating, but let's break it down a little bit.t=Xˉ1−Xˉ2s2(1n1+1n2)t = frac{bar{X}_1 – bar{X}_2}{sqrt{s^2 left(frac{1}{n_1} + frac{1}{n_2}right)}} The above formula is for what is called the T-Statistic. Its components are interpreted as:

  Now for the Pooled Variance. In short, Pooled variance is a weighted average of the variances of the two above samples. As a reminder, variance is the squared difference between each value of a group and the mean of said group, finally divided by the number of the group – 1. the formula for Pooled Variance is:sp2=(n1−1)×s12+(n2−1)×s22n1+n2−2s_p^2 = frac{(n_1 – 1) times s_1^2 + (n_2 – 1) times s_2^2}{n_1 + n_2 – 2} Where:

It might be worth noting that the denominator,n1+n2−2{n_1 + n_2 – 2} is the calculation for the Degrees of Freedom (DF), which will be a critical calculation in many other statistical operations.   After calculating through these equations, the final step is to reference a T-Distribution table with your Degrees of Freedom and the level of significance (p value) you wish to use, and see if the value is larger than the referenced table value. If the equation value is more than the reference value, then your results could be considered significant. Otherwise, any differences are likely to be due to chance. With the underlying math out of the way, let's look at how we can do a T-Test in R, using real world data.  

Calculating A T-Test in R

As usual, if you'd like to follow along with full code write-up and data, please go to Cody’s Github and download the T-Tests folder.

Step 1: Library set up

For our tutorial, we're only going to need the base R packages, and tidyverse which is mostly used for our data cleaning. We can install and load this library using the following:

Step 2: Collect and Format Data

Now, we can take a look at our data. For this tutorial, we'll be borrowing some data from the Northern Irish Statistics and Research Agency (NISRA), particularly their data around the number of suicides in North and South Belfast Assembly Areas from 1997 to 2018. We can have as a null hypothesis that there is no difference in suicide rates between North and South Belfast.  I've pulled a CSV which has two rows (one for North Belfast, another for South), and the columns are Assembly.Area and then every other column is a year with an X in front of it. This closely resembles data you're likely to experience in the field, as it's a mess and not formatted how we'd like. Let's quickly read in the file, and then look into all of the column names except the first, and remove  any X's in front of the years.

Now that our data is cleaner, we can format it a bit. While there are perhaps more efficient ways to go about it, I think this makes for a good time to look at long and wide dataframe transformations. As our data is now, it'd be very hard to fit into a T-Test calculation, as we cannot easily iterate across columns to collect the values (counts per year) we need for our groups (location). It could be said to be very wide. Let's transform it to a longer format.

Here, we've taken our dataframe and "piped"%>% it so we can do multiple transformations on it. We then used the pivot_longer function to rearrange our dataframe, by making sure our Assembly Area keeps as a column, but then making two new columns, Year and Count. Year is essentially taking the names of the original dataframe columns and putting them as a row value, and then taking their value and saving it as Count. This does make the data a bit cleaner, but ideally we'll have to make this a bit wider by have a separate column for each of our location groups, and a reference column to our Year. This will look remarkably similar to above.

Now that our data is properly formatted, let's get to testing.

T-Test in R: The Easy Way

The easiest way to run a T-Test in R, now that we have our data formatted, is just calling the T-Test function against our groups, like so:

When we look at t_test_result in our Console, we can see that there's a very significant difference between the two locations.

  And there we have it.  

T-Test in R: The Hard Way

  Say for whatever reason, you don't quite trust the above function to do all the hard work for you and want to handle this all manually. Then, we can use the code below which is fairly self-explanatory (given the above mathematical discussion). There isn't too much to delve into as it's mostly simple calculations that are absent any complex functions.

Conclusion

Here, we took a look at what T-Tests are, the math underneath the term, and even how to use them in R to answer a question about suicide rates in Northern Ireland.  

Humanities Moment

This tutorials painting is Bangor, Belfast Lough by James Arther O'Conner (Irish, 1792-1841). A landscape painter with a rather incredible reputation, O'Connor exhibited his work at the Royal Academy in London, England in 1822. His works often feature a notable sense of depth and atmosphere, capturing the moody and dramatic skies, lush countryside, and the serene beauty of rivers and lakes. He had a talent for rendering light and shadow, which added a dynamic and often poignant quality to his landscapes.  

Epi Explained: Understanding T-Tests

T-tests are a foundational tool in statistics and public health, enabling researchers to make inferences about population means when the population standard deviation is unknown and the sample size is small. This entry of Epi Explained delves into the intricacies of T-tests, covering their types, applications, and the mathematical principles in a way that should be easy enough for anyone to understand.

Introduction to T-Tests

At its core, a T-test is a type of inferential statistic (a statistical analysis that uses a small sample of the population to determine traits about the larger whole) used to determine if there is a significant difference between the means of two groups, which may be related in certain features. It’s widely used in research to compare the averages of two samples, especially when dealing with small sample sizes and when the population’s standard deviation is unknown.

Historical Context

The T-test was developed by William Sealy Gosset, a chemist working for the Guinness brewery in Dublin, Ireland, in the early 1900’s. Due to proprietary concerns, Gosset published his work under the pseudonym “Student,” which is why the T-test is sometimes referred to as the Student’s T-test. It was originally designed as a way to monitor the quality of the famous Stout, without using too much of it in testing. The T-test was formally published in 1908, and has seen constant use ever since.

Mathematical Foundation

The T-test is built on the premise that when a population is normally distributed, the small sample means will also be normally distributed around the population mean. The formula to calculate the T-statistic varies depending on the type of T-test being performed, so we’ll go over each one by one. Keep in mind that there is a lot of variable overlap, so we’ll cover each once as they appear.

Types of T-Tests

There are four types of T-tests, each designed for specific situations:

One-Sample T-Test:

Independent Two-Sample T-Test (also known as an unpaired T-test):

Paired Sample T-Test:

Welch’s T-Test:

For all T-Tests, Degrees of Freedom are calculated (either by subtracting 1 from the sample size or following the equation for Welch’s T-Test) and then used as a reference number against a T-distribution Table. If the result of your T-Test is greater than the value of the T-distribution table, then you can reject the null hypothesis H0 H_0 that states that there is no significant difference between the two observations, and accept the alternative hypothesis HaH_a that there is a significant difference.

Application in Research

T-tests are indispensable in various sub fields of public health, whether one has an interest in Environmental Health (say to compare the mean concentration of pollutants and lung function in populations), Epidemiology ( Looking at potential higher rates of a condition after suffering a specific illness), or Global Health (comparing infant mortality rates between countries).

Practice Problems

1. A public health researcher wants to investigate the effect of a new community-based exercise program on reducing stress levels among adults. To do this, the researcher measures the stress levels (using a standardized stress assessment tool) of 50 participants before they start the program and then again after they have completed the 8-week program.

Which type of T-test should the researcher use to analyze the data?

A) One-Sample T-Test
B) Independent Two-Sample T-Test
C) Paired Sample T-Test
D) Welch’s T-Test

2. A Mental Health Epidemiologist is curious as to whether the adults in their community have a sleep duration significantly different from that of a national average of 7 hours. In a study involving 25 adults, it was found that the sample mean was 6.5 hours, and the standard deviation was 1 hour. Say they are using a significance value of 0.05. What would the T-Statistic be, and would it be significant?

3. A Health Education Specialist is comparing the effectiveness of two different health education programs on improving knowledge about diabetes management. Program A was delivered to a group of 30 participants, and Program B was delivered to a group of 40 participants. The specialist measured the increase in knowledge scores (out of 100) before and after the programs and calculated the following statistics:

The specialist decides to use Welch’s T-test to determine if the difference in mean knowledge score increases between the two programs is statistically significant, given the differences in sample sizes and variances. Assuming a significance level of 0.05, which of the following outcomes is correct?

A) The difference in means is not statistically significant.
B) The difference in means is statistically significant, and Program B is more effective.
C) The difference in means is statistically significant, but it’s not clear which program is more effective.
D) The sample sizes are too small to conduct Welch’s T-test.

Answer Key, click to reveal

C, -2.5 and Significant, B

Conclusion

T-tests offer a robust method for comparing means across different samples, making them a crucial part of the statistical toolkit for public health practitioners. If you’re interested in how to do T-Tests via R or Python, we have tutorials available for both.

In any case, thank you for reading this entry of Epi Explained. Check back regularly for more public health content!

Humanities Moment

The featured image for this article was Portrait of Mrs Robert Celestin Guinness (Dickie) (1935) by Philip Alexius de László (Hungarian, 1869–1937).  Philip Alexius de László, an Anglo-Hungarian painter renowned for his portraits of royal and aristocratic figures, was born in Budapest into a Jewish family and later became a British citizen in 1914. He pursued art education in Hungary, Munich, and Paris, achieving early acclaim with a portrait of Pope Leo XIII, and settled in London in 1907 after marrying Lucy Guinness (who was part of the so-called “banking branch” of the Guinness family more commonly known for brewing). Despite his successful career, honored by numerous awards and ennoblement, de László faced internment during WWI due to accusations of enemy contact but was later exonerated; he died in 1937 from heart problems, but not before his art was featured in the 1932 Olympics.

Epi Explained: Understanding Odds Ratio

Odds Ratio (OR) is a fundamental concept in epidemiology and statistics, providing a measure of association between exposure and outcome across different groups. This concept is pivotal in fields like medicine, public health, and social sciences, where understanding the relationship between risk factors and outcomes can guide critical decisions. This edition of Epi Explained delves into the intricacies of Odds Ratio, elucidating its definition, calculation, and interpretation, supplemented by historical context, real-world applications, and an example problem to enhance comprehension.

Introduction to Odds Ratio

The Odds Ratio is a measure that compares the odds of an outcome occurring in the presence of a particular exposure, to the odds of the same outcome occurring without that exposure. It’s a metric that helps researchers understand the strength and direction of the association between two binary variables.

Historical Context and Importance

The concept of odds and their ratios has been around for centuries, primarily in gambling contexts. However, its application in epidemiology and statistics gained prominence in the 20th century as researchers sought quantifiable measures to investigate the link between potential risk factors and disease outcomes. The OR became especially crucial in case-control studies, where direct risk estimation is not feasible due to the study’s retrospective nature.

Mathematical Definition

The odds of an event is defined as the probability of the event occurring divided by the probability of the event not occurring. Mathematically, if P P

is the probability of an event, the odds is given by: Odds=P1−P{\text{Odds} = \frac{P}{1 – P}}

Simply put, this equation reads as “Odds can be calculated as the probability of an event occurring (P){(P)}, divided by the probability of the event not occurring (1−P){(1 – P)}“.

The Odds Ratio (OR) is then calculated as the ratio of two odds:

Odds Ratio (OR)=Odds of exposure in casesOdds of exposure in controls=A/CB/D=A×DB×C{\text{Odds Ratio (OR)} = \frac{\text{Odds of exposure in cases}}{\text{Odds of exposure in controls}} = \frac{A/C}{B/D} = \frac{A \times D}{B \times C}}

Calculation of Odds Ratio

To calculate the OR, data is often arranged in a 2×2 contingency table based on two binary variables: exposure (yes/no) and outcome (yes/no).

Outcome PositiveOutcome NegativeExposedabNot Exposedcd

It is then fed into the above equation to calculate a value. If your value is higher than 1, then those in an exposed condition have higher odds of developing the outcome, and the reverse is true if the value is between 0 and 1. Do keep in mind though that this does not mean that the odds are significantly higher or lower, as that depends on how you are calculating significance.

Interpretation of Odds Ratio

Practice Problem

Consider a study investigating the association between smoking (exposure) and lung cancer (outcome). The data might look something like this:

CancerNo CancerSmokers100200Non-Smokers30270

Get the Odds Ratio for the above table.

Answer Key, click to reveal

D. 4.5

OR=100⋅270200⋅30=270006000=4.5 

This OR of 4.5 suggests that smokers have 4.5 times the odds of developing lung cancer compared to non-smokers.

Limitations and Considerations

While the OR provides valuable insights, it has limitations. It can overestimate the risk, especially for common outcomes. Moreover, it does not imply causation and can be influenced by confounding variables. Understanding the context and design of the study is crucial for accurate interpretation.

Conclusion

The Odds Ratio is a versatile and powerful statistical tool in epidemiological studies, offering insights into the relationship between exposures and outcomes. Its calculation and interpretation require careful consideration of study design and context.In this edition of Epi Explained, we have:

Come by again next week for another edition of Epi Explained.

Humanities Moment

This articles featured artwork is Woman Reading (1913) by Rik Wouters (Belgian, 1882 – 1916). Wouters, though short lived (dying at the age of 34 due to illness during World War 1), created over 200 paintings and sculptures and is known for a simplistic, straightforward style with warm colours and simple motifs. This simplistic and elegant approach also tended to shy away from any symbolism within his art; What you see is what you got, without the need of some grand narrative.

Calculate an odds ratio in R

Introduction

Odds Ratio (OR) calculations are a cornerstone in public health research, providing insights into the strength of association between an exposure and an outcome. In this ThuRsday Tutorial, we’ll explore how what an Odds Ratio is, as well as how to calculate it in R.

Understanding Odds Ratio

Odds Ratio (OR) is a measure used in epidemiology to compare the odds of an event occurring in one group to the odds of it occurring in another group. This is especially useful in case-control studies where you’re comparing the odds of exposure in cases (those with the disease or outcome of interest) to the odds of exposure in controls (those without the disease).

Odds as a Concept

Before diving into odds ratios, it’s important to understand what “odds” are. In a health context, odds are a way of representing the likelihood of an event happening. If the probability of an event happening is P, the odds are calculated as:

Odds=P1−P{text{Odds} = frac{P}{1 – P}}

Simply put, this equation reads as “Odds can be calculated as the probability of an event occurring (P){(P)}, divided by the probability of the event not occurring (1−P){(1 – P)}“.

Calculating the Odds Ratio

Now, consider a case-control study with the following data:

The odds of exposure among the cases is A/C{A/C}, and the odds of exposure among the controls is B/D{B/D}​. The odds ratio is calculated as:

Odds Ratio (OR)=Odds of exposure in casesOdds of exposure in controls=A/CB/D=A×DB×C{text{Odds Ratio (OR)} = frac{text{Odds of exposure in cases}}{text{Odds of exposure in controls}} = frac{A/C}{B/D} = frac{A times D}{B times C}}

Interpretation of the Odds Ratio

Limitations

It’s important to remember that odds ratios can sometimes overestimate the risk, especially if the outcome is common. Also, they do not necessarily imply causation.

For more explanation on the underlying mathematics and mechanics of Odds Ratios, please check out our Epi Explained series! For now, let’s get on with the calculation of Odds Ratios in R.

Odds Ratio in R: Smoking and Cancer

For our tutorial, we’ll run with a fairly simple assignment. If you’d like to follow along with this tutorial, download the folder for Odds Ratio on Cody’s Github. Imagine that you’ve been handed a dataset by a senior epidemiologist, where you need to figure out if smokers have a higher odds of presenting with two cancer diagnoses, either malignant mast cell neoplasms (C96.29) or malignant neoplasm of unspecified part of unspecified bronchus or lung (C34.90).

Preliminaries: Installing and Loading Required R Packages

Before diving into the analysis, ensure you have the necessary libraries. Install and load ‘dplyr’ for data manipulation and ‘epiR’ for epidemiological analysis in R, as shown below:

Importing and Preparing the Dataset

Now we can import our sample data, saved as “smoking_survey.csv”. To help better simulate real world data, this spreadsheet isn’t quite the format we’d need for our analysis, so we’ll need to do some cleaning. For now, we can call the base R function read.csv() to put our data into a dataframe.

Now we can inspect our data and see there’s 3500 rows of 5 variables. X appears to be just a counter, smoking_status seems to be filled with either “smoker” or “non-smoker”, age is the age of the person, diagnosis_codes appears to be a list per person of various ICD-10 codes, and then we have a zipcodes field.

Data Transformation for Analysis

Next, we select the relevant variables: smoking_status and lung_cancer. We can then create a function to mark ‘yes’ for lung cancer diagnosis based on specific codes and ‘no’ otherwise. This next bit of code might be tricky for new users, so let’s break it down.

Here, we did the aforementioned selection of columns we want to deal with using dplyr::select(), telling it to reassign our dataframe to just these values.  Our next step is to create what is called a function. Functions are pieces of code that can be run multiple times or be used to organize certain operations in a way that results in cleaner code. As a rule, if you’re doing something more than twice, or if it’s something that might require some alterations in future (say, needing to add a new diagnosis to search for), a function can be the way to go. What we are doing is creating a function called has_lung_cancer which takes in the argument codes.

Next, it creates an if statement, where if there is a match to the condition, the code does one operation, and if it doesn’t, another takes place, or the operation is passed over. In this case, we’re using the grepl operation to scan through our column of choice to look for first “C34.90” and then “C96.29”. If it matches in either case ( || is an “OR” operator) then we get a value of “yes” returned, otherwise “no”. Keep in mind that this match can be at any point in our column for each row, so it can start with the code, end with the code, or have it somewhere in the middle and it won’t matter as it’s just looking for a match and ignoring everything else through what are called Regular Expressions (ReGex), which will be a later topic.

Applying the Diagnosis Function

Now we can actually apply this new function to our dataset, and have something that’s much easier to work with. Here, what we’ll do is create a new column in smoking_survey called lung_cancer. We’ll then fill this field by taking the smoking_survey dataframe, and going down row-wise (the 1 indicates we’re going down rows, where 2 would indicate going across columns), and apply a function that calls the has_lung_cancer function down the diagnosis_codes column.

From there, we just do another selection operation to get rid of our diagnosis codes, and then turn our column values into a data type called factors . In short, factors are basically categories that make things easier to arrange, and we then tell R within our factor call to make 2 specific categories for each column, and how they should be arranged for future use.

Creating a Contingency Table

A contingency table lays the foundation for calculating Odds Ratio. We can create a table with smoking_status and lung_cancer to visualize the distribution using the table() table. We can see that there’s very obviously a difference in counts, especially accounting for the uneven sample sizes of smokers and non-smokers. Now that we have our contingency table, we can calculate our Odds Ratio manually. This is a rather simple operation as all we need to do is take our smokers groups and dvide them by our non-smokers groups (our with event and without events). the [Y,X] after our table name basically points out the position, where Y is our Column and X is our row.

And there we have it, how to create our Odds Ratio manually, arriving at a value of 5.77, which indicates smoking does increase the likelihood of getting cancer profoundly. However, there’s another process that can provide us these values as well as many other statistics to examine if that value is significant.

Using the epiR Package for Odds Ratio Calculation

The ‘epiR’ package simplifies this process. We use the epi.2by2 function for a more comprehensive analysis, including confidence intervals. All we need to do is set our method to cohort count, set a confidence level, and get a quick format to return the results in.

Now we can check the results in our terminal:
A statistical results table for our project, showing significant results.

Conclusion

Here, we’ve learned what Odds Ratios are, how to calculate them both by hand and in R, and how to leverage both functions and the EpiR library to make our analysis easier and more comprehensive.

Humanities Moment

The featured image of this article is Small River House (1913)  by Amadeo de Souza-Cardoso (Portuguese, 1887 – 1918). Initially influenced by impressionism and then by cubism and futurism, this Portuguese painter became a pioneer of modern art around 1910, known for his aggressive, vivid style that often verged on abstractionism or dadaism. His participation in the 1913 Armory Show in the U.S. marked the beginning of a highly experimental career, though he didn’t gain wide public recognition until the 1950’s.

Calculate and visualize correlation in Python

  Correlation is a statistical measure that describes the extent to which two variables change together. In data analysis tasks, understanding correlation can often help in identifying relationships between variables. This tutorial will guide you through calculating and visualizing correlation using Python.

Understanding Correlation in Epidemiology: Context and Limitations

Before we cover correlation analysis in Python, we should first establish what correlation is, what types of correlation exist, potential uses and the limitations of the measure. This understanding is crucial for applying correlation analysis appropriately and interpreting its results accurately in any context, but especially when it comes to research that might directly impact the lives of entire populations.

What is Correlation?

Correlation is a measure that illustrates the degree to which two variables are associated with each other. For example, one might look into an association between environmental factors (like air pollution levels) and health outcomes (such as asthma rates). Understanding these correlations is fundamental in identifying potential risk factors and health trends.

What are the Types of Correlation?

  1. Positive Correlation: If an increase in one variable (e.g., tobacco use) tends to be associated with an increase in another (like lung cancer incidence), this is positive correlation.
  2. Negative Correlation: Conversely, a negative correlation occurs when an increase in one variable (e.g., vaccination rates) is associated with a decrease in another (like the incidence of the targeted infectious disease).
  3. No Correlation: There are instances where no discernible pattern exists between two variables, suggesting no apparent relationship.

Generally, correlation is denoted as 'r', with a value from -1 (total negative correlation) to +1 (total positive correlation), with values closer to 0 being seen as having little or no correlation. It should be noted though that what might constitutes a weak correlation or no correlation will likely depend on multiple factors.

Relevance in Epidemiological Studies

Correlation is a vital statistical tool in epidemiology for:

Key Limitations in Correlation Analysis

As with any statistical measure, the value of correlation can vary and comes with significant caveats:

For more information on Correlation, please check out our Epi Explained article on Correlation.

How to Perform a Correlation in Python

With the key background out of the way, let's dig into how to do a correlation in Python with some data that is similar to what you may encounter in the field. If you'd like to follow along with the code,please check out Cody’s Github and download the folder for the Correlation Tutoria l.   Our task during this tutorial is fairly simple. You have been assigned a quick analysis to see if there is a correlation between people getting sick with Cholera or Influenza and their proximity to a suspected source of illness, Well A. We can look at the raw correlation figure, as well as do some graphing that can illustrate any potential relationships.

Step 1: Read in the Libraries and Data.

Starting out, let's first install some key packages and then read them into the environment. Please note this tutorial assumes you already have Python and some IDE (Integrated Development Environment) installed, and if you've yet to do so, please do so now.

Packages (or Libraries, both are used interchangeably in most cases) are basically bundles of code, functions and data that can be imported into your project that don't require you to do everything by hand. Here, we're importing pandas and numpy to do some data formatting and numbers work, while matplotlib , seaborn and plotly all have different graphing capabilities we'll use together. It should be noted that the part of the code that goes

as pd , etc. is a way to shorten your call to specific libraries and is a fairly standard practice in Python.   Next, we need to read in our data. this is fairly simple as we call pd.read_csv from pandas , and tell it to go into the Data folder, and in that folder find our disease_dataset.

  We can take a look at what we're dealing with now.  

Step 2: Data Cleaning

A table showing various diseases and their distance from a fictional Well "A"

As we can see, we have two columns, one with the name of the disease and the other with the distance of the well marked. Further looking into it, there appears to be 3 noted diseases, both influenza and cholera which we expected, as well as a group called "No Enteric Diseases". These entries aren't particularly of use to us, so we can ignore them. What we can't really ignore is that the data isn't formulated in a way that makes life easy for us. To do a proper correlation, we will need to do the following steps:

  1. Separate out the diseases into unique groups.
  2. Take these groups and see if they can be further grouped together by distance to Well A.
  3. Summarize the number of visits by distance.

To do this, we can write what's known as a function. Functions are pieces of code that can be used for the same purpose more than once, and are a great way to shorten up analysis files.  

The group_by_distance function first filters the dataset for the specified disease, then groups the filtered data by distance from Well A, and counts the occurrences of the disease at each distance. The result is a new dataframe, which is grouped by the distance from Well A, by number of occurrences, and creates a new column called

count_A which shows the number of cases for each distance. We then call our function on our dataframe, to create both Cholera_Distance and Flu_Distance, which have the distance as the first column, and then the count of occurrences of the disease as the next column.  

Correlation and Graphing

  Once our data is all set up, correlation is a remarkably easy task. We can just call the correcoef function from numpy . What we're doing is feeding in the distance variable and the count variable we created, and then grabbing a part of the resulting array where there is an examination of the relationship between the two variables. It should be noted that by default, this function gives an array of the correlation of all variables and how they relate to each other (including themselves) so checking on output order of the results is fairly important. For the last bit of the script, we're just printing out the correlation values for both Influenza and Cholera.

We can see that the correlation between flu and distance from the well is very weak at .09, indicating no real correlation is taking place. That said, Cholera has a decent negative correlation of -0.47, which indicates that the farther someone is away from the well, they are also less likely to get sick with cholera.   Say though that simple figures aren't quite enough and we need some graphs to put into a report, and an additional graph another Epidemiologist can interact with for more detailed information. We can finally play with graphing capabilities. First, let's knock out the static graphs.

There's a lot going on with the code segment above, so let's break it down. For both graphs, we're first setting how big our graphs will be (10 inches by 6 inches) by using plt.figure . Then, we're using

Seaborn to make a a scatter plot of our two variables of interest, as well as creating a regression line over it. Next, we're formatting the title and labels before finally printing our finished plot using

plt.show()

      Lastly, we can do a similar operation using plotly to create some interactive graphs. This is quite a bit more condensed but follows the same general idea of defining the x and y axis, setting a trend line, and then making a title.

This can then be printed, or used in a dashboard, or embedded like it is here.

Conclusion

In this tutorial, we've covered:

If you've found this article helpful, please feel free to drop by again next and every friday for another PyFriday Tutorial. Or, check in every day for new research, core concepts, and programming content.  

Humanities Moment

The featured image of this article is Odysseus And Polyphemus (1896) by Arnold Böcklin (Swiss, 1827-1901). Böcklin, a Swiss symbolist painter known for his imaginative interpretations of classical and mythological subjects, is most celebrated for his "Isle of the Dead" series, evoking themes of death and mortality within fantastical settings. His work, embodying the romantic and symbolist aesthetics of the late 19th century, has been both admired for its technical mastery and critiqued for its anachronistic style.

Calculate and visualize correlation in R

    Correlation is a statistical measure that describes the extent to which two variables change together. In epidemiological data analysis, understanding correlation helps in identifying relationships between variables. This tutorial will guide you through calculating and visualizing correlation using R.

Understanding Correlation in Epidemiology: Context and Limitations

Before we cover correlation analysis in R, we should first establish what correlation is, what types of correlation exist, potential uses and the limitations of the measure. This understanding is crucial for applying correlation analysis appropriately and interpreting its results accurately in any context, but especially when it comes to research that might directly impact the lives of entire populations.

What is Correlation?

Correlation is a measure that illustrates the degree to which two variables are associated with each other. For example, one might look into an association between environmental factors (like air pollution levels) and health outcomes (such as asthma rates). Understanding these correlations is fundamental in identifying potential risk factors and health trends.

What are the Types of Correlation?

  1. Positive Correlation: If an increase in one variable (e.g., tobacco use) tends to be associated with an increase in another (like lung cancer incidence), this is positive correlation.
  2. Negative Correlation: Conversely, a negative correlation occurs when an increase in one variable (e.g., vaccination rates) is associated with a decrease in another (like the incidence of the targeted infectious disease).
  3. No Correlation: There are instances where no discernible pattern exists between two variables, suggesting no apparent relationship.

Generally, correlation is denoted as 'r', with a value from -1 (total negative correlation) to +1 (total positive correlation), with values closer to 0 being seen as having little or no correlation. It should be noted though that what might constitutes a weak correlation or no correlation will likely depend on multiple factors.

Relevance in Epidemiological Studies

Correlation is a vital statistical tool in epidemiology for:

Key Limitations in Correlation Analysis

As with any statistical measure, the value of correlation can vary and comes with significant caveats:

For more information on Correlation, please check out our Epi Explained article on Correlation.

How to Perform a Correlation in R

With the key background out of the way, let's dig into how to do a correlation in R with some data that is similar to what you may encounter in the field. If you'd like to follow along with the code, please check out Cody’s Github and download the folder for the Correlation Tutorial.   Our task during this tutorial is fairly simple. You have been assigned a quick analysis to see if there is a correlation between people getting sick with Cholera or Influenza and their proximity to a suspected source of illness, Well A. Ideally, we can look at the raw correlation figure, as well as do some graphing that can illustrate any potential relationships.

Step 1: Read in the Libraries and Data.

Starting out, let's first install some key packages and then read them into the environment. Please note this tutorial assumes you already have R and RStudio/Posit installed, and if you've yet to do so, please do so now.

Packages are basically bundles of code, functions and data that can be imported into your project that don't require you to do everything by hand. Here, we're importing ggplot2 for some static graphs that one could copy and paste into a report as an image file, plotly for some interactive graphs that allow for closer examination of details, and dplyr for some additional data analysis functionality.   Next, we need to read in our data. this is fairly simple as we call the "read.csv" function, and tell it to go into the Data folder, and in that folder find our "disease_dataset".  

We can take a look at what we’re dealing with now.

Step 2: Data Examination and Cleaning

A capture of the dataframe for the Correlation project, with two columns stating disease and distance to wellAs we can see, we have two columns, one with the name of the disease and the other with the distance of the well marked. Further looking into it, there appears to be 3 noted diseases, both influenza and cholera which we expected, as well as a group called “No Enteric Diseases”. These entries aren’t particularly of use to us, so we can ignore them. What we can’t really ignore is that the data isn’t formulated in a way that makes life easy for us. To do a proper correlation, we will need to do the following steps:

  1. Separate out the diseases into unique groups.
  2. Take these groups and see if they can be further grouped together by distance to Well A.
  3. Summarize the number of visits by distance.

To do this, we can write what's known as a function. Functions are pieces of code that can be used for the same purpose more than once, and are a great way to shorten up analysis files.  

Here we've created out function, "Group_by_Distance". The function itself takes in df, which is any dataframe, and a string called Disease_String which in our use case will be "Cholera" or "Influenza". The function then takes this string and filters down the dataframe by finding matched inside the dataframes Disease column, and returning all columns from that (hence the comma before the end bracket). From there, we take that filtered dataframe and organize it into groups of data depending on the distance value, and finally count the number of data points within each subgroup.   We then call our function on our Dis_Data dataframe, to create both Cholera_Distance and Flu_Distance, which have the distance as the first column, and then the count of occurrences of the disease as the next column.

Correlation and Graphing

  Once our data is all set up, correlation is a remarkably easy task. We can just call the cor() function within base R and print the results as follows, or assign the value to a variable.

We can see that the correlation between flu and distance from the well is very weak at .09, indicating no real correlation is taking place. That said, Cholera has a decent negative correlation of -0.47, which indicates that the farther someone is away from the well, they are also less likely to get sick with cholera.   Say though that simple figures aren't quite enough and we need some graphs to put into a report, and an additional graph another Epidemiologist can interact with for more detailed information. We can finally play with ggplot2 and Plotly a bit. First, let's knock out the ggplot graphs.

There's a lot going on with the code segment above, so let's break it down. For both graphs, we're first calling the ggplot function to create a graph. Next, we're stating we want to use our newly created dataframes data, with the X axis being the distance column, and the y axis being the count of cases. We're then adding the geom_point function in to dot out where the cases are, and then a geom_smooth command with a linear regression method to show a general trend line, without any confidence intervals (these topics will be covered in later articles). The last steps are ensuring that both X and Y axes are continuous in nature, so they're normal counts with limits of 25 each, with each axis starting at 0 before going to 25. Lastly, we create some labels to make our graph easier to read.  

      Lastly, we can do a similar operation using plotly to create some interactive graphs. It should look very similar, with the exception being the "~", which is a formula indicator mark.

  This can then be printed, or used in a dashboard, or embedded like it is here.

Conclusion

In this tutorial, we've covered:

If you've found this article helpful, please feel free to drop by again next and every Thursday for another ThuRsday Tutorial. Or, check in every day for new research, core concepts, and programming content.  

Humanities Moment

The featured image of this article is Still Life with Books and a Violin (1628) by Jan Davidsz de Heem (Dutch, 1606-1684). De Heem, renowned as one of the Netherlands' greatest still life painters, was celebrated for his vivid color harmony and precise depiction of various objects, ranging from flowers and fruits to lobsters and butterflies. His work, known for its opulence and often carrying moral messages, ranged from abundant displays to simple arrangements, frequently incorporating symbolic elements like skulls and chalices to reflect on life, death, and salvation.

Understanding Correlation

Why correlation matters in public health

Public-health datasets often contain variables that move together: temperature and heat illness, age and blood pressure, vaccination coverage and disease incidence, or deprivation and access to care. Correlation gives analysts a compact way to describe one aspect of that pattern. It is often a useful beginning for exploration—but it is not a study design, a causal estimate, or an explanation by itself.

Read the scatterplot before the coefficient

A coefficient compresses many paired observations into one number. Before calculating it, plot the data. A scatterplot can reveal whether the relationship is roughly linear, whether one observation dominates the result, whether groups differ, or whether a curved pattern would be hidden by a coefficient near zero.

Maximum summer temperature and heat-related emergency visits in six example neighborhoods A scatterplot with six points rising from lower left to upper right. Maximum temperature increases from 78 to 94 degrees Fahrenheit while heat-related emergency visits increase from 3 to 10 per 10,000 residents. 788285889194 357911 Maximum temperature (°F) Heat-related ED visits per 10,000
Example data show a strong positive linear association. The dashed line summarizes the pattern; it does not prove what caused the differences among neighborhoods.

Worked example: heat and emergency visits

Suppose an analyst compares the maximum summer temperature with heat-related emergency-department visits across six fictional neighborhoods. Each row is one paired observation.

NeighborhoodMaximum temperature (°F)Heat-related ED visits per 10,000
A783
B824
C855
D887
E918
F9410
Small fictional dataset used consistently through the worked example.

For these six pairs, Pearson’s r is approximately 0.987. That is a very strong positive linear association in this small dataset: neighborhoods with higher maximum temperatures also had higher rates of heat-related emergency visits.

A correct interpretation stops there. The calculation alone does not show how much of the difference was caused by temperature. Tree canopy, housing quality, air conditioning, age distribution, occupational exposure, measurement differences, and other factors may influence both the observed temperatures and emergency visits. Because the rows describe neighborhoods, the result also cannot establish that the individuals with greater heat exposure were the individuals who visited an emergency department.

What Pearson’s r measures

Pearson correlation coefficient

r=∑(xi−x¯)(yi−y¯)∑(xi−x¯)2∑(yi−y¯)2

What every symbol means

r
The correlation coefficient you are calculating. It will be between −1 and +1.
x
The first variable. Here, x is maximum temperature.
y
The second variable. Here, y is heat-related emergency visits.
i
The row you are working on. For example, row 1 is neighborhood A.
x̄ and ȳ
The mean, or ordinary average, of all the x values and all the y values.
∑
Capital sigma means “add all of these up.” It is an instruction, not another variable.
²
Square the number: multiply it by itself. For example, 3² = 3 × 3 = 9.
√
Find the square root: the number that, multiplied by itself, gives the value inside the symbol.

The basic idea: first ask whether each pair is above or below its two averages. Then combine those movements and scale the result so different datasets can be compared on the same −1-to-+1 range.

Calculate it yourself

Use the formula with the six neighborhoods

You can follow these steps with paper and a basic calculator. Keep two decimal places while you work; the tiny rounding difference at the end is expected.

Step 1: Find the two averages

Add the six temperatures and divide by 6. Then do the same for the six visit rates.

x̄ = (78 + 82 + 85 + 88 + 91 + 94) ÷ 6 = 86.33
ȳ = (3 + 4 + 5 + 7 + 8 + 10) ÷ 6 = 6.17

Step 2: Work across each row

Subtract the appropriate average from each value. For neighborhood A, the temperature difference is 78 − 86.33 = −8.33 and the visit-rate difference is 3 − 6.17 = −3.17. Multiply those differences, then square each difference. Repeat for every row.

Areax − x̄y − ȳMultiply the differencesSquare the x differenceSquare the y difference
A−8.33−3.1726.3969.4410.03
B−4.33−2.179.3918.784.69
C−1.33−1.171.561.781.36
D1.670.831.392.780.69
E4.671.838.5621.783.36
F7.673.8329.3958.7814.69
Add each column0.000.0076.67173.3334.83

The first two columns add to zero because differences above and below an average balance one another. The last three totals are the numbers the formula needs.

Step 3: Put the totals into the formula

r = 76.67 ÷ √(173.33 × 34.83)
r = 76.67 ÷ √6037.78
r = 76.67 ÷ 77.70

r ≈ 0.987

The positive sign tells us the two variables tend to rise together. The value is close to +1, so the six points follow a strong straight-line pattern. It still does not tell us that temperature alone caused the differences.

Try changing one value

Replace neighborhood F’s visit rate of 10 with a much lower number, such as 4. Recalculate the y average and the affected columns. The coefficient will become smaller because the last point no longer follows the upward pattern as closely. This is a useful way to see how one observation can change a correlation.

Pearson’s r ranges from −1 to +1. The sign gives the direction of the linear association. The absolute value summarizes how closely the points follow a straight-line pattern. A value near +1 indicates a strong positive linear association; a value near −1 indicates a strong negative linear association; and a value near 0 indicates little linear association.

Near zero does not mean “no relationship.” A strong U-shaped or other nonlinear pattern can produce a Pearson correlation close to zero. A large coefficient also does not guarantee that a straight line is the most useful summary. Always interpret the coefficient beside a plot and the study context.

How strong is strong?

There is no universal threshold that turns a coefficient into “weak,” “moderate,” or “strong” for every field. The practical meaning depends on measurement reliability, expected biological or social variation, sample size, the range of values studied, and the decision the analysis must support. Report the coefficient, show the data, and explain the context instead of relying on a label alone.

When Spearman rank correlation is useful

Spearman’s rank correlation describes a monotonic relationship: as one variable increases, the other tends consistently to increase or decrease, even when the pattern is not a straight line. It operates on ranks and can be useful for ordinal data or monotonic relationships that do not meet Pearson’s linear framing. Tied ranks require the standard tie-aware calculation used by statistical software; the familiar shortcut formula without a correction is not generally exact when ties are present.

Four common interpretation mistakes

  1. Calling association causation. Confounding, reverse causation, selection, and measurement can all produce or distort correlation.
  2. Skipping the plot. Outliers, clusters, curved patterns, and data errors can disappear inside one number.
  3. Assuming zero means unrelated. Pearson’s r can miss strong nonlinear relationships.
  4. Comparing coefficients without context. Restricting the observed range or changing how variables are measured can change the coefficient.

Knowledge check

Across several counties, vaccination coverage and disease incidence have a Pearson correlation of −0.72. Which conclusion is best supported?

  1. Vaccination caused incidence to fall by 72%.
  2. Higher coverage was associated with lower incidence in a fairly strong linear pattern.
  3. Seventy-two percent of disease cases occurred in unvaccinated people.
  4. No other county-level factor could explain the pattern.
Show the answer and reasoning

B is the supported interpretation. The sign indicates that higher coverage tended to occur with lower incidence, and the magnitude describes a fairly strong linear association in these data. The coefficient is not a percentage, does not estimate an individual vaccine effect, and does not rule out confounding or ecological bias.

A brief history—and an ethical boundary

Francis Galton and Karl Pearson helped develop correlation while studying heredity, and both were central advocates of eugenics. University College London’s institutional history documents how early biometry and eugenics developed together. That history is not a decorative footnote: it shaped institutions, human classifications, and the questions the methods were built to answer. Using correlation today does not endorse eugenics, but responsible analysis requires scrutiny of how variables are defined, whose data are collected, and which decisions a result may support.

Humanities Moment

Johann Carl Loth

German painter · 1632–1698

Loth was a seventeenth-century painter whose Diogenes shows the ancient philosopher raising a lamp while searching for an honest person. The work is the article’s featured image and was sourced from Artvee by Broadly Epi.

Why this work: the lamp offers a modest visual metaphor for careful inquiry. A correlation can illuminate a pattern, but an honest analysis keeps searching for alternative explanations, limitations, and what the calculation cannot establish. The painting provides context; it is not statistical evidence.

Sources and further reading

Exploratory data analysis in R

In our last article, we covered how to handle reading in CSV and XLSX data into R and some basic cleaning of said data. Today, we’re going to go from properly reading in the data, to making data products and figuring out what it can tell us. Let’s take a look at how to do Exploratory Data Analysis in R. To follow along in this Exploratory Data Analysis, feel free to pull the data and code from our GitHub.

Data Background

Before we get into the analysis portion of the article, let’s first take a key step in any exploratory data analysis and do some background work on the table we’re working with.

As you may recall, we are using the Northern Irish Statistical and Research Agency (NISRA)’s collection of reported suicide records from 1970 until 2018. For today’s exercise, we’ll actually be only looking at one table we made in our last article, Table 3, or the recorded rate per 100,000 by Sex. This table has only a couple of main variables that we need to pay attention to. These are the Registration Year, the counts of Male and Female presumed cases, and the total count of presumed cases per Registration Year.

While most are self-explanatory, the term Registration Year may seem a bit ambiguous. Simply put, this was the year in which the case was registered with the Coroner, which means, as you might expect, there were often delays from the event to the registration. In the original Excel workbook released by NISRA, table 13 shows the median lag between event and registration from 2001-2018. Though we cannot be sure, we can assume with some level of safety that those dates before 2001 had at least as much as the median delay, which means any analysis we perform has to have a caveat that the particular count of any one year might actually be a delayed effect of a particularly bad year previous.

On the topic of data constraints, we are also limited by the ability to define what suicide is to any level of certainty. Certainly, back when I worked primarily with suicide and overdose data, this was always a problem. We cannot be in someone’s mind post-event, and so our estimates will always be imperfect to some degree, so looking at general trends is perhaps most beneficial. For NISRA’s standards, they are counting a case using the following definition:

In the UK, in considering suicide events it is conventional to include cases where the cause of death is classified as either ‘Suicide and self-inflicted injury’ or ‘Undetermined injury’. The ICD codes used for ‘Suicide and self-inflicted injury’ are X60-X84 and Y87.0 (ICD9 E950-E959), and the ICD codes used for ‘Undetermined injury’ are Y10-Y34 and Y87.2 (ICD9 E980-E989).

-NISRA

This can be seen as a slightly conservative approach, though by no means an incorrect one, and may one day be a topic unto itself. But for now, that’s enough background on what the data is and the limitations therein, let’s get to seeing what this data can actually tell us.

Exploratory Data Analysis – Data Read-In and Basic Statistics

Since we will be dealing primarily with numerical data in this exercise, our first tasks are going to be quite easy. Step one, of course, is reading in our data just like we did last time. We’ll save it as a DataFrame called Rate_Per_100k, just to make sure we remember what we’re looking at should we need a quick break.

#Load in packages for later use
pacman::p_load(
  tidyr,
  ggplot2,
  plotly
)
# Read in File
Rate_Per_100k <- read.csv("table3.csv")

Now upon inspection, we’re seeing one extra variable called X that we really don’t need.

DataFrame Output which shows index variable X equal to the row number, alongside expected values

That’s not ideal, so we’ll clean that up really quickly using a method similar to what we’ve done in the past. Just instead of deleting a row, we’ll take out a column using:

Rate_Per_100k <- Rate_Per_100k[,-1]

Recall that calling a DataFrame in this way is telling R to retain all rows (empty before the comma), and all but the first column. Now that we’ve got that cleaned up, we can go about calculating some basic statistics. For this exercise, we’ll calculate the Mean, Median, Standard Deviation, Variance, Minimum value and Maximum values for the Male, Female and Total columns. We could repeat several commands in the script a few times, or we could build what’s called a function and make life a bit easier for ourselves.

# We want to create 3 seperate DataFrames for Male, Female, and Total. Since a lot will be repetition, let's use something called a function.

Core_Stats <- function(DataFrame, colname){
  
  #for these calculations, we need to pull from the list of values, transform them into a numeric vector, then run the calculations
  Avg <- mean(as.numeric(unlist(DataFrame[colname])))
  Median <- median(as.numeric(unlist(DataFrame[colname])))
  StD <- sd(as.numeric(unlist(DataFrame[colname])))
  Variance <- var(as.numeric(unlist(DataFrame[colname])))
  Min <- min(DataFrame[colname])
  Max <- max(DataFrame[colname])
  Category <- colname
  
  Core_Stat_Block <- data.frame(Category,Min, Max, Avg, Median, StD, Variance)
  return(Core_Stat_Block)
}

Here, we are creating a function we can use multiple times called Core_Stats. For Core_Stats, we’ll feed in the name of a DataFrame (in this case, Rate_Per_100k), as well as a column name (“Male”, “Female”, or “Total”). From there, we take the fed in DataFrame and create variables for the above-listed statistics. To make sure everything is correctly computed, we take the original DataFrame Column, which is considered a list, and then unlist it to a vector that is then interpreted as a vector of numbers. If this doesn’t make sense immediately, that’s okay. We’ll cover data types in a future article, but for now, know the general rule that math operations don’t like working with lists, so when we see them, we need to transform them. For reference, min() and max() don’t quite require this reworking as it’s acting more like a search function. Lastly, we grab the colname so we can use it as a label, combine all the variables into a DataFrame and return it out of the function.

Since the function is now done, let’s test it out by creating 3 DataFrames, one per column of interest, combining them, and doing away with the intermediate DataFrames.

Female_CS <- Core_Stats(Rate_Per_100k, "Female")
Male_CS <- Core_Stats(Rate_Per_100k, "Male")
Total_CS <- Core_Stats(Rate_Per_100k, "Total")

#Now row bind (rbind) them to one DataFrame. Can use for tables later
Stats_DataFrame <- rbind(Female_CS, Male_CS, Total_CS)

#and remove unneeded DFs
rm(Female_CS, Male_CS, Total_CS)

This creates a DataFrame which can then be turned into tables, which again we’ll cover in another article. An example of such a table is below:

Category Min Max Avg Median StD Variance
Female 2.799695 8.025987 5.417896 5.217563 1.597635 2.552437
Male 5.676500 27.137226 15.774356 14.328779 6.360067 40.450452
Total 4.353541 17.394765 10.482895 9.197285 3.718632 13.828223

The table does give us some quick and useful insights. Namely, every single statistical measure points to those assigned Male at birth had a higher rate of suicide cases per 100,000 individuals and much more variability in case numbers, despite Male and Female being somewhat even in the country (49% and 51% respectively) and the population being above 1.5 million since 1970 and currently reaching nearly 2 million people. But what this does not tell us easily is if this initial analysis is due to a spike, or is a common trend in time. Plus, it’s a touch hard to read, so let’s look at making some visuals.

Exploratory Data Analysis – Creating Graphs

So before we can make some graphs, we need to do a tiny bit of data cleaning and make our data long as opposed to wide, which was covered in our previous article. In short, we turn the Male, Female and Total columns into one column we name ASAB (Assigned Sex at Birth), and use the Count field to keep track of the number of cases per ASAB per Registration Year.

Rate_Per_100k <- Rate_Per_100k %>%
  tidyr::pivot_longer(cols = c("Male", "Female", "Total"))

#rename columns
colnames(Rate_Per_100k) <- c("RegYear", "ASAB", "Count")

One of the biggest reasons to use R, period, is how very easy it is to create graphs in R and customize every little detail. As such, it’s also a great advantage when doing XDA (Exploratory Data Analysis), as you can really dig into the data quickly, and go from idea to image easily. To prove this, let’s make a quick box plot using ggplot2, one of the best graphics libraries for R.

#Create Boxplot
BoxPlot <- ggplot2::ggplot(data = Rate_Per_100k) +
  geom_boxplot(mapping = aes(x = ASAB, y = Count)) +
  labs(title = "Suicides per 100,000, 1970-2018 by Assigned Sex at Birth",
         subtitle = "Median based Box Plot",
         caption = "Data source: NISRA.gov.uk")

In the above code, we call ggplot2’s ggplot to draw a graph using our Rate_Per_100k DataFrame. We then use the plus symbol to tie in another graphical function to tell ggplot2 we want a box plot, with the X to be Sex, and Y to be the Count of cases. The labs, as you may have guessed, are labels to be used. This produces the following:

A box and whisker plot of suicides in Northern Ireland by Sex, showing a great deal of disparity across sexes.

This essentially covers the same information as the table above did, but does it in a way one can understand at a glance. Now let’s look at how to do some timeseries-based analysis using an interactive library, plotly.

Plotly is another graphing library that is formatted similarly to ggplot2, but provides the advantage that the images are not static, so they can provide more information and even allow for some filtering. The code for our next graph is as follows:


#Create interactive graph using Plotly
plotly::plot_ly(data = Rate_Per_100k, x = ~RegYear, y = ~Count, color = ~ASAB) %>%
  add_lines()  %>% 
  layout( title = "Interactive Timeseries: Suicides by Sex and Year, 1970-2018" , xaxis = list(title = 'Registration Year'),yaxis = list(title = 'Rate per 100k'))

Here, we are taking the plot_ly function, similar to ggplot2’s ggplot function, and telling it we want to use our DataFrame, and to iterate down values using “~” in front of column names. We’re then piping in the add_lines() function to put lines between the default scatter plot, and then piping again to get our titles in. The end result for us is something somewhat simple, but given that it’s 4 lines of code, mighty impressive as well.

As we can see, there’s a general upward trajectory in Males, and it’s mostly flat for Female cases, but there is a remarkable spike in 2006. This may lead us to further look at the years 2004-2006 to see what may have changed.

Exploratory Data Analysis – Findings and Conclusion

Given our table and graphs, we can say that Suicide Cases which are registered are more likely to be from Males. They also have less stable case rates overall, and we may want to look at the mid-2000s and what may have happened during that time period to greatly increase the case counts before they stabilized in the ensuing decades. For Female cases, we may want to look at the early 1970s, early 1980s, and mid-2000’s to also see what may be contributing factors.

As you may have guessed, Exploratory Data Analysis is, more than anything, a starting point. We don’t have answers, and we have no promise of answers, but we do have some initial findings which could lead us to greater insights. We also know around what times we should look for events or factors, down from 5 decades to maybe 10 if we’re being particularly thorough for any one demographic. I would in particular also look for different ways the data has been chopped up to see if more information could be gained.

In this article, we covered what an Exploratory Data Analysis looks like for primarily Numeric data, and how to present some basic findings. If you’d like to test it out yourself, please visit our GitHub to download the code and data. In the future, we will be looking at how to do XDA on text data, starting a whole series on Natural Language Processing.

Read CSV and Excel files in R

If you haven’t gotten the email, you will soon. “Hey there, I was wondering if you could tackle an analysis of this data? Thanks!” The tone’s cheery, and surely this shouldn’t take too long, right? How much data can be emailed in an Excel file? And they’re all tables, computers love tables, right? Well, not always. But don’t worry! In this article, we’re going to tackle how to read Excel files into R, both the common CSV files and the more complex XLSX workbooks. Be sure that if you haven’t yet, download R and RStudio. Let’s get into it.

Read Excel Files in R

Hate it or love it, Excel has been a mainstay of both Public Health for quite a long time. It’s become such an “old reliable” in our field that it’s been at the heart of several major incidents, such as when Public Health England relied on Excel (admittedly, an archaic file format for Excel called XLS) a bit too much and lost 16,000 COVID swab test results. Incidents aside though, when working at any level in the field, you’re sure to get emailed excel tables that look great, at least originally.

The problem lies in what is easy for computers to read, versus what is easy for humans to read. You see, we like titles up at the top telling us what the point of a table is. We like formatted tables that combine and chop up groups, ages, whatever, so we can note any strange patterns or comparisons. And by whatever Almighty you believe in, do we ever love having more than 1 observation per row of a table. We often use these factors to decide how to build tables for each other, but what do computers like? Let’s kick on RStudio and see first what it sees from a formatted table, and then what we need to do to fix it.

Starting out, we’re going to grab an Excel workbook from the Northern Ireland Statistics and Research Agency. Specifically, we’re going to be pulling their death counts from 1970-2018 which are presumed to be suicides. We will be looking to use this data in other analyses in future articles, and thus making sure we read the data correctly is crucial. If you’d like, you can pull these files from the NISRA website itself, or via my Github, in the DataSets section. Upon opening up the file, you’ll see that there is quite a selection of tables that we could pick from, but for today’s exercise, I’m going with Table 2 and Table 3.

For both tables, we’ll need to do a bit of the same process, but let’s go through the operations on each table individually as practice. Let’s begin by just looking at what Table 3 looks like in Excel, not in R quite yet.

Read Excel Files in R – Easy File

An image showing the rows and columns of a rate per 100,000 population from 1971 to 2018 in Excel.

Okay, so that doesn’t look too bad. We have a clear title, labels for each column, and even a nifty categorization of Male and Female as Sex. Whoever designed this did a great job in terms of readability. Now that we know what it’s supposed to look like, let’s get some code going.

Before we can read in the excel file into our R environment, we need to load the necessary libraries. You can think of libraries as packages of prebuilt tools you can use in your programming to make life significantly easier. Typically, if you need to install a singular package, one can use the following:

install.packages("pacman")

In this case, we’re looking to install the package pacman, from the Comprehensive R Archive Network, or CRAN. Pacman is incredibly useful as it has a function called “p_load”, which checks to see if you have the packages you need installed. If they are, then it simply loads those packages into the environment you’re working in. If not, it will install, then load those packages, which is great for sharing code. In general, you want to keep your install.packages() commands outside of your main script (use the console at the bottom), while “p_load” can be used in the script, as seen below:

pacman::p_load(
  readxl
)

Here, we’re telling R that we want to dig into the pacman package, find the “p_load” function, and then use it to load in readxl, which is a library that’s used to, as you might guess, better read excel files. We can now use read excel to bring in that xlsx file into the R environment and take a look at how R sees the excel file. Below, what we’ll do is name a variable (basically a data storage container) Table_3_DataFrame, and we’ll define its contents as the result of reading an xlsx sheet, namely the one found at the path name, and then the specific sheet called “Table 3”. Do keep in mind that if your R code is not saved to the same folder as your excel document, you’ll need to lengthen your path to find it. For instance, it could be “C:/User/Sheets/” and then the file name.

Table_3_DataFrame <- readxl::read_xlsx(path =  "00_Suicide_2018_NOT_CLEANED.xlsx", sheet = "Table 3")

Good, now we can click on the table icon next to the newly named DataFrame to see how it looks.

An image after reading in the xlsx table into R studio. There are multiple gaps in titles, odd spacing, and other errors.

That isn’t great. But that’s alright, let’s list off some of the issues we see off the top. So for the column names, it did catch the title of the whole table, and did bring in the right number of columns. We also have all the data after the table titles looking just fine, and it looks like row 3 could really be our column header without any real editing. We have a plan forward, let’s just cut off everything above row 3.

To do this, we really need to only adjust the read in command we just did to something a touch more specific.

readxl::read_xlsx(path =  "00_Suicide_2018_NOT_CLEANED.xlsx", range ="Table 3!B4:E52")

Now, instead of using just sheet, we’re actually using a range argument instead, which takes in the table, then an exclamation point to denote where that title ends, and then the upper left, and lowest right cells that contain data. As a general piece of advice, you can find a lot of information by using the following in the console to find out more about certain functions:

?Package::FunctionInPackage

This will open up a small page in Rstudio that will let you know all the fun things you can do with any specific function, and is probably the most useful command you’ll use outside of bringing packages in. Anyways, back to the task at hand, with this new parameter of range, let’s see how we did.

A properly formatted table from Table 3 using the range argument in read_xlsx

Perfect, we have column headers where they need to be, and the data is clean and easy to read. We can now save this as a CSV file if we so wish, and move on to the next table.

write.csv(Table_3_DataFrame, file = "Table3.csv")

As with our read-in, we can also change where the file is saved with a path before the “Table3.csv” file name. Now for a real challenge.

Read Excel Files in R – Challenge File

Now that we have a nice warmup done, let’s take a look at a much more challenging table, Table 2, shown here:

Complex Age Group and Sex table that includes null values, zeroes, and lots of formatting

So now we have null values represented by “-“, zeroes, some of the formatting issues we saw earlier, and a lot more column entries that would be hard to work with in R, as R is more oriented towards going down rows and not across columns for many functions. As before, let’s take a look at what happens when we read in the Excel data into R.

pacman::p_load(readxl, zoo, # We'll need this and tidyr later for some special functionstidyr)Table_2_DataFrame <- readxl::read_xlsx(path =  "00_Suicide_2018_NOT_CLEANED.xlsx", sheet = "Table 2!B3:T151")

A very messy table with misaligned column headers and missing values

It doesn’t get much worse than that. We have all the problems we already saw off the bat in the excel sheet, and misaligned columns, plus a bunch of rows without years. This would be useless for analysis, so let’s break down what we need to do into a few steps:

  1. Set the columns to have names in their proper places.
  2. Find a way to get those entries with missing years their proper year assigned
  3.  Pivot the data from a wide format as it currently is, to a long format so that each age group gets its own row as opposed to its own column.
  4.  Reformat any labels as needed.

Step 1, we can perform a simple enough operation of just cutting off that first row entirely that has mostly numeric-based titles and then renaming the columns by age group. You might wonder why we don’t just push the numeric-based titles up, and mostly it’s to ensure that there aren’t weird interpretation errors in R. As a rule, you don’t want variables to start with a number. So, we can subtract the row in question by calling a DataFrame to assign its values to itself, except for that first row, as seen here:

Table_2_DataFrame <- Table_2_DataFrame[-1,]

In this case, the square brackets tell R you want to do something inside a variable, and within DataFrames you can (usually) treat the square brackets as holding two values in format X,Y. In this case, we want all but the first X (row), and we want all columns, so we put nothing there after a comma. Now that we’ve got that bit sorted, let’s handle renaming everything.

 colnames(Table_2_DataFrame) <- c("RegYear", "ASAB", "AllAges", "AgeGroup1", "AgeGroup2", "AgeGroup3", "AgeGroup4", "AgeGroup5","AgeGroup6", "AgeGroup7", "AgeGroup8","AgeGroup9", "AgeGroup10", "AgeGroup11", "AgeGroup12", "AgeGroup13", "AgeGroup14", "AgeGroup15", "AgeGroup16")

Now, this seems clunky, and you might be asking the great question of why we don’t just name the Age Groups as their respective numbers (i.e., 05-17). This is primarily because naming variables or column headers with numbers is seen as bad practice and can cause errors.

With that out of the way, we can now fill in those missing year values. This is an easy enough problem to logic out, we just take a look at the RegYear value, and if it’s empty, fill it in with the value that came before it. the zoo package is super handy for this sort of work.

Table_2_DataFrame$RegYear <- zoo::na.locf(zoo::na.locf(Table_2_DataFrame$RegYear),fromLast=TRUE)

Every year is filled in, so now it’s time for something a bit weird. As the table is now, it’s termed as “wide”, which is to say the observations are considered the years, and the different number of people in each age group is part of that observation. To make analytics easier, later on, we’re going to make it “long”, which is to say each year, and each age group will be its own observation.

Table_2_DataFrame <- Table_2_DataFrame %>%tidyr::pivot_longer(cols = starts_with('AgeGroup'))

Since you’ve been paying attention to the code up to this point, you might think this looks very strange. Namely, what does “%>%” do in R? What is it, even? “%>%” is called a pipe, from the magrittr package, and what it does is for more complex function calls, or for multiple function calls using the same dataset, makes it so you needn’t retype anything. The %>% tells R “Take this data, and default to it being the object I want to do stuff on in future functions”. You can link multiple pipes together, and in one particular script I bore witness to a 100-line long piping operation. As a general rule, and as a personal plea, don’t do that. Once the piping is done, the function to make the DataFrame longer is told to make the columns that start with “AgeGroup” into a reference to our new rows. Keep in mind due to this operation, some column names changed.

Next, we can take out those pesky “-” values and replace them with R’s native Null value, NA. The reason we do this is to ensure that age value columns can be converted from a string value, which can’t be manipulated numerically, to a numeric column that can only contain null or numeric values.

Table_2_DataFrame$value[Table_2_DataFrame$value == "-"] <- NA

Almost done now. All that’s left is renaming the Age Groups, some column names, and turning Assigned Sex at Birth (ASAB) into a factor (category), and our counts of cases into a numeric column.To change the values of age groups, we’ll call the data frame, then look for the value “name”, which is what those AgeGroups ended up changing to. Then, we’ll tell R to look for values in that column that are equal to the value of that age group, and reassign the values.  To change the columns, the names() function acts similarly.

 #replace AgeGroups
NI_DF["name"][NI_DF["name"] == "AgeGroup1"] <- "Under 15"
NI_DF["name"][NI_DF["name"] == "AgeGroup2"] <- "15-19"
NI_DF["name"][NI_DF["name"] == "AgeGroup3"] <- "20-24"
...
NI_DF["name"][NI_DF["name"] == "AgeGroup15"] <- "80-84"
NI_DF["name"][NI_DF["name"] == "AgeGroup16"] <- "85+"

#Or if you want a quicker way about it, try creating a list of the year groups and age groups and iterate down them.#We'll cover that in a later article.

names(NI_DF)[names(NI_DF) == 'name'] <- 'AgeGroup'
names(NI_DF)[names(NI_DF) == 'AllAges'] <- 'AllAgesCounts'
names(NI_DF)[names(NI_DF) == 'value'] <- 'Counts'
NI_DF$ASAB <- as.factor(NI_DF$ASAB)
NI_DF$Counts <- as.numeric(NI_DF$Counts)
 

And there we have it, now we can save the results into a CSV file to use later. Speaking of CSVs, let’s cover how to quickly read CSV files into R.

Read CSV Data in R

Unlike what we’ve covered so far, reading in CSV files is remarkably straightforward. This is due to the fact that by definition, CSV files typically have very little room for formatting customization and thus R can usually be depended on to read in these files with no problem.

To practice, we’re just going to pull in a CSV we already made from the previous section. All you really need is “read.csv” from the Utils package which is bundled up in base R. So, instead of a few steps like we did above to get the data into a properly readable state, we just need the following one-liner:

Test_DF <- read.csv("Table3.csv") 


And there you have it. As a note, I have seen a few people try just using “read.csv” without assigning it a variable, which R will allow you to do, it just isn’t terribly useful unless you are planning some very complex manipulations as the data comes in. Instead, defining a DataFrame variable as we did above is the norm.

This concludes our short article on how to read Excel files in R. In our next article, we’ll explore how we can go about performing some exploratory data analysis on a few of these files. As usual, if you’d like to try out some operations on the same data used in this article, or check out the full code solutions to what we did today, check out my personal Github, where I have a folder for each article written.

Install Python and a Python IDE

Python has quickly gained traction as a competitor and companion to R in the world of data analysis. As such, being able to use this immensely versatile language is quickly becoming an essential skill in epidemiology work. Here, we’ll take the first steps on your Python journey by going through how to download Python, as well as a suite of tools including an Integrated Development Environment, PyCharm.

How To Download and Install Python

home screen of python.orgTo get started on our journey with Python, first, you must download it from the official source, which is conveniently called python.org. Once you are on the home page, head over to the downloads tab, and select the page for your specific OS. On the OS page, you should select the “Latest Python 3 Release” if you have a more modern OS, or otherwise select Python 3.7.13 if you have any PC with anything more recent than Windows XP.

The reason we are selecting Python 3 instead of Python 2 is that Python 2 is being sunset for most uses, and has some fundamental differences between itself and 3, which seems like it will continue onward as the standard Python version for some time.

displaying python command line

After selecting the version you wish to download, simply scroll down to the “Files” section of the release, and select your preferred method of installation. For most, the Windows or macOS installers will be useful, and for Linux users, the tarball will probably work best. In any case, select your install method, wait for the download to complete, and then open the file. From that point, an installation should take place that may need permissions and should complete itself in a matter of seconds.

As a last check, be sure to go to your computer Search bar and type “py”. You should see the Python version you’ve downloaded as an option, and open it. The screen should look similar enough to a normal command prompt. Go ahead and close it out for now, as we discuss for a moment why you might need an IDE as opposed to just developing code for python using that environment.

Do I need a Python IDE like PyCharm?

                In short, yes. Could you run through most analyses of datasets using only the command line? Probably, yes. But using an IDE has very many benefits, such as making it easy to save and debug your work, sharing that work with colleagues, and some even making writing code much faster. One such IDE is PyCharm by JetBrains. PyCharm includes such functionality as code completion, optimization, and simple corrections as well, which makes development quite a bit quicker than it would be otherwise. For this tutorial, we’ll be installing PyCharm through Anaconda, which is a free suite of different tools that can be useful throughout a project or analysis life-cycle. Let’s take a look at how to get you started.

How to install  Anaconda and PyCharm

Anaconda HomepageTo download Anaconda, simply go to anaconda.com, and at the home page, either hit download or select the icon of your OS and then select your installer. Due to there being so many tools packaged within Anaconda, it can be quite a sizable download of around half a gigabyte.

Once it’s downloaded, an installation wizard will appear on opening. Agree to the terms, then select your destination folder. I would suggest keeping this on your local drive (usually the C: Drive) and creating its own folder. From there, select any advanced options you wish and hit install. After a few moments, you should be able to hit next again and encounter an offer to view the Anaconda Individual Edition Tutorial and Getting Started with Anaconda, which you can view if you so wish.  From there you can hit the finish button and you’re all set.

Going forward in these tutorials, we will be using a tool within Anaconda that’s made by JetBrains called PyCharm. It’s a lovely IDE that is very feature-rich and even has fairly informative error handling which can help you spot errors and fix them quickly, which is usually a daunting task with any level of analysis. To open PyCharm, open Anaconda and wait for it to load for a moment.  From there, select “Launch” under PyCharm, and you should be all set.

How do I get started with PyCharm?

Pycharm GUI, with highlights on the touring and tutorial tabsUpon opening PyCharm for the first time, you might be a little lost on how to get started, and that’s alright. Luckily, the PyCharm team has made some excellent tutorials on their IDE and made them immediately available to you upon opening. While it might be tempting to dive right in and click New Project, instead give the onboarding tour a quick go, and then once you’ve completed that, play around in the Learn PyCharm tab. Both of these steps will help build an understanding of the IDE you’re working with and will make learning Python much faster as you won’t have to juggle learning the tools and the language at the same time.

Once you have the tutorials completed, it’s a good idea to set up some folders to put your eventual python files and projects so that your computer doesn’t become a mess of such files. Also, structuring where you’ll be putting things will help you in the future if you wish to use something like Github for sharing and improving your code.

Summary

In this article, we’ve quickly covered how to download one of the most versatile programming languages around, Python. We also quickly covered how to download Anaconda, a suite of data analysis tools and IDEs, and how to get started with PyCharm, which will be used in future articles. Our next articles will cover the basics, including variable creation, data importation, and Exploratory Data Analysis in both Python and R.