The Susceptible-Exposed-Infected-Recovered (SEIR) model is a natural extension of the SIR Model, accounting for a fourth category of disease state, Exposure. For this ThuRsday Tutorial, we'll cover how to not only make a quick SEIR model but also how to graph the results. If you'd like a decent background on what all goes into the SIR model conceptually and mathematically, please check out our Epi Explained article for Understanding SIR Models , or to see the more simplistic model in action you can also check out the previous SIR model ThuRsday Tutorial article. As usual, if you'd like to play with the code on your own, you can download it through Cody’s Github.
Step 1: Installing and Loading Necessary Packages
Just like last time, we'll be using two primary packages in this tutorial. The two packages we'll be using are deSolve and plotly.
deSolve is a package for solving differential equations in R, which we’ll use to solve the SEIR model equations.
plotly allows for creating interactive plots, which will enable us to visualize the dynamics of the SEIR model effectively.
GitHub Gist
Step 2: Defining the SEIR Model
Incorporating the Exposed compartment modifies our approach from the original SIR model slightly. Now, we have four states: Susceptible (S), Exposed (E), Infected (I), and Recovered (R). The transitions now include a movement from Susceptible to Exposed before individuals become Infectious. Here's how we set up the SEIR model in R:
GitHub Gist
Now on first look this might be a bit strange even to experienced R users as the function seems to do very little with what we're inputting, but in reality this is because we're actually going to use this function in yet another function in Step 3. For now though, let's do a quick run-through of what we're just set up.
The function takes three arguments:
time: The current time point. While not directly used in the differential equations, it is required by the ode function from the deSolve package.
variables: A vector containing the current numbers of susceptible, infected, and recovered individuals (S, E, I, R).
parameters: A vector of parameters for the model, specifically beta, gamma, sigma, and N (the total population).
Within the function, we use the with function to combine
variables and parameters into a single list, which simplifies accessing these values. The with function allows us to refer to elements of the list directly by their names (e.g.,S,
E,I,
R, beta,
gamma,sigma,
N) within its code block.
The rates of change for each compartment are then calculated according to the SEIR model equations:
dS: The rate of change of susceptible individuals is the negative product of the infection rate (beta), the number of susceptible individuals (S), and the number of infected individuals (I), divided by the total population (N). This represents the number of new infections per time unit.
dE represents the rate of change for the Exposed population, transitioning from Susceptible due to infection and moving towards Infectious as the incubation period ends. The parameter sigma controls the rate at which Exposed individuals become Infectious, adding a new dynamic to the model.
dI: The rate of change of infected individuals is the number of new infections (as calculated for dS) minus the number of recoveries, which is the product of the recovery rate (gamma) and the number of infected individuals (I).
dR: The rate of change of recovered individuals is simply the number of recoveries, as calculated in the dI equation.
Finally, the function returns a list containing the rates of change for each compartment, which is then used by the ode function to solve the model over time.
Step 3: Setting Initial Conditions and Parameters, Then Solving
Before solving the model, we need to specify the initial conditions (i.e., the starting numbers of susceptible, infected, and recovered individuals) and the parameters (beta,
sigma, and gamma) which control the disease transmission, incubation period and recovery rates, respectively. Here, we start with a population of 1000 individuals, with only one infected person as the outbreak begins. The parameter values are hypothetical and can be adjusted based on the disease's characteristics you're modeling (the incubation period is seen as an inverse, so we have an incubation period of five days, thus a parameter value of 1/5). With the function we already made and initial setup ready, we can now solve the differential equations using
deSolve's ode function, which will return the solutions to every step from day 0 to day 50.
GitHub Gist
Step 4: Visualizing the Results with Plotly
Finally, to understand the dynamics of the disease through time, we'll visualize the results using plotly. This step transforms the output into a dynamic and interactive plot that can is much easier to understand, and can often wow your desired audience.
GitHub Gist
This is a fairly simply plotly graph, but it's worth noting that for each class, we need to create a separate trace for each line, which allows them to act independently of one another.
The output can be seen here:
Conclusion
Through this tutorial, you've learned how to implement and visualize the SEIR model in R using deSolve and plotly. This model as mentioned earlier is a natural extension of the SIR compartmental model, though by no means should be seen as the last one. In fact, there are dozens of potential compartmental models that include things like vaccination, spatial relationships, and much more.
Humanities Moment
This ThuRsday Tutorial's featured image is Cat Family by Sophie Sperlich (German, 1863-1906). An artist from Munich, Sperlich is famed for paintings of both cats and dogs in particular, and while not much is known of her life outside of her work, she has gained renewed popularity in recent years. In fact, since 2008, 38 of her works have been sold at auction, for anywhere between $100 and $1800.
Epi Explained: Understanding Cohort Studies
Cohort studies are a common study method throughout public health and intervention methods. By following groups of people who are alike in many ways but differ by a certain characteristic, researchers can uncover links between specific exposures and health outcomes. This Epi Explained will delve into the essence of cohort studies, elucidating their importance, methodology, types, and real-world applications, along with their strengths and limitations.
Introduction to Cohort Studies
What is a Cohort Study?
A cohort study is a longitudinal observational study design that follows a group of people (a cohort) over a period to determine how certain exposures affect specific outcomes. The term “cohort” originates from the Latin word “cohors,” meaning a group of people moving together. In epidemiology, this group shares common characteristics or experiences within a defined period.
Key Features of Cohort Studies
Prospective or Retrospective: Cohort studies can be forward-looking (prospective), where participants are followed over time from exposure to outcome, or backward-looking (retrospective), where researchers look back at historical data to link exposures to outcomes.
Comparison Groups: They typically involve at least two groups — one exposed to a certain factor and the other not (control group) — to compare the incidence of outcomes over time.
Observational: Unlike randomized controlled trials, the investigator does not assign exposures; they only record what happens naturally.
How Do Cohort Studies Work?
Selection of Participants
The first step in a cohort study is defining and selecting the cohort. Participants are chosen based on their exposure to a certain factor or factors of interest before the onset of the disease or outcome being studied.
Exposure Assessment
Researchers then categorize the participants into groups based on their level or type of exposure. Exposures can range from environmental factors and lifestyle choices to genetic predispositions.
Follow-up Period
Participants are followed over time to observe the development of new cases of the outcome of interest. This period can last from a few days to several decades, depending on the condition being studied.
Data Analysis
The incidence rates of the outcome are calculated for each exposure group. Statistical analyses, often using Cox proportional hazards models or logistic regression, are applied to estimate the risk associated with the exposures, adjusting for potential confounders. Usually these results are reported in terms of significance, as well as effect size, so as to give a decent overview of whatever the study was observing.
Types of Cohort Studies
Prospective Cohort Studies
Prospective cohort studies monitor participants from exposure into the future, allowing researchers to observe how the disease progresses and how risk factors may change over time. This approach is powerful for studying rare exposures but can be time-consuming and expensive.
Retrospective Cohort Studies
Retrospective studies utilize existing records to identify cohorts and trace back in time to assess exposures. This method is faster and less costly but may be limited by the availability and accuracy of historical data.
Ambidirectional Cohort Studies
Combining elements of both prospective and retrospective designs, ambidirectional studies offer a dynamic approach to understanding disease processes, leveraging historical data while continuing to follow participants into the future. This isn’t a commonly used method, but in certain cases the added complexity and caveats may be worth the additional insights.
Applications of Cohort Studies
Cohort studies have been instrumental in identifying risk factors for chronic diseases, such as the link between smoking and lung cancer or the association between diet and cardiovascular disease. They also play a crucial role in evaluating the effectiveness of interventions over long periods.
Strengths and Limitations
Strengths
Temporal Sequence: Cohort studies can clearly establish the sequence of events, from exposure to outcome, providing strong evidence for causality.
Wide Range of Outcomes: They can investigate multiple outcomes for any one exposure.
Direct Measurement of Incidence: These studies allow for the direct calculation of risk and incidence rates.
Limitations
Time and Cost: Prospective studies, in particular, require significant time and financial investment.
Loss to Follow-up: Participants may drop out or be lost over time, potentially biasing the results.
Confounding Variables: While statistical methods can adjust for known confounders, unknown or unmeasured factors can still bias the findings.
Conclusion
Cohort studies are a powerful tool in epidemiological research, offering insights into the complex interplay between exposures and outcomes. By meticulously following groups of individuals over time, these studies provide critical evidence that can inform public health policies, medical practices, and individual choices. Despite their challenges, the depth and breadth of knowledge gained from cohort studies make them indispensable in the quest to understand and improve human health.
Humanities Moment
The featured image for this Epi Explained is Twenty Young Girls in a Group Walking to the Left by
Thomas Stothard (English, 1755-1834). Thomas Stothard was an influential English painter, illustrator, and engraver, known for his book illustrations and designs for textiles, who eventually became a full academician and librarian at the Royal Academy. His son, Robert T. Stothard, also a painter, is notable for his depiction of the proclamation of Queen Victoria’s accession in 1837 outside York Minster.
The Susceptible-Infected-Recovered (SIR) model is a fundamental concept in epidemiology, offering insights into how diseases spread and recede in populations over time through a relatively simply set of functions. For this ThuRsday Tutorial, we’ll cover how to not only make a quick SIR model but also how to graph the results. If you’d like a decent background on what all goes into the SIR model conceptually and mathematically, please check out our Epi Explained article for Understanding SIR Models. Now, let’s get to coding. As usual, if you’d like to play with the code on your own, you can download it through Cody’s Github.
Step 1: Installing and Loading Necessary Libraries
We have to start with setting up the Python environment by installing and importing the necessary libraries. For this tutorial, we'll utilize numpy for numerical operations,
scipy for solving differential equations, and plotly for interactive visualizations.
numpy is crucial for handling arrays and mathematical functions.
scipy offers powerful options for numerical integration and solving differential equations, playing a pivotal role in our model’s computation.
plotly enables the creation of dynamic plots, allowing us to present the SIR model’s dynamics, as well as allow for users to see more minute details that otherwise wouldn’t be available.
GitHub Gist
Step 2: Defining the SIR Model
The essence of the SIR model lies in its compartmental approach, segmenting the population into Susceptible (S), Infected (I), and Recovered (R) groups. The transitions between these states are governed by differential equations. Here's the Python function that does all the mathematical heavy lifting:
GitHub Gist
In this function:
variables holds the current counts of Susceptible, Infected, and Recovered individuals.
N, beta, and gamma represent the total population, infection rate, and recovery rate, respectively.
Step 3: Initial Conditions, Parameters, and Solving
Prior to solving the model, initial conditions (i.e., initial numbers of S, I, R individuals) and parameters (beta and gamma) need specification. In our scenario, we consider a population of 1000, with a single initial infection. These parameters are flexible and should reflect the specific disease dynamics being modeled, as well as your population of interest. The differential equations are solved using scipy.integrate.odeint, yielding the system's evolution over time.
GitHub Gist
Step 4: Visualizing the Outcome with Plotly
The culmination of our efforts is visualizing the disease's progression. By leveraging plotly, we transform our model's output into an interactive graph, offering a clear and engaging depiction of the epidemic's dynamics.
Creating a plot in
plotly involves adding traces for each population compartment (S, I, R), each with its distinct color and style, facilitating an intuitive grasp of the model's implications.
GitHub Gist
It should be noted that in Python, graphs often require initialization (hence the empty go.Figure() call). Otherwise, a lot of this code is actually very similar to how R handles graphing if you are familiar with that. Below is our interactive output:
Conclusion
Through this tutorial, we've navigated the implementation and visualization of the SIR model using Python, showcasing the model's utility in understanding infectious disease dynamics. While the SIR model provides a foundational perspective, it simplifies real-world complexities such as population heterogeneity and spatial dynamics. Future tutorials will explore more nuanced models like SEIR and network-based models, offering a deeper dive into epidemiological modeling.
Humanities Moment
This PyFriday Tutorial's featured image is Sir Tristram defeats Sir Palamedes in Ireland (1902) by
Arthur Rackham (English, 1867-1939). Arthur Rackham, a pivotal figure in the Golden Age of British book illustration, is celebrated for his distinct pen and ink drawings enhanced with watercolour, a skill refined from his journalistic illustration background. His innovative use of colour-separated printing for the Early American tale marked a significant advancement in book production. Rackham is best known for his illustrations in classics like Rip Van Winkle, Peter Pan in Kensington Gardens, and the Fairy Tales of the Brothers Grimm. After starting his career in journalism and illustration, Rackham fully committed to book illustration by 1894, achieving fame with his unique style, especially after the publication of Rip Van Winkle in 1905. He lived and worked in various locations around London and Surrey, contributing significantly to children's literature until his death in 1939.
Build an SIR model in R
The Susceptible-Infected-Recovered (SIR) model is a fundamental concept in epidemiology, offering insights into how diseases spread and recede in populations over time through a relatively simply set of functions. For this ThuRsday Tutorial, we'll cover how to not only make a quick SIR model but also how to graph the results. If you'd like a decent background on what all goes into the SIR model conceptually and mathematically, please check out our Epi Explained article for Understanding SIR Models. Now, let's get to coding. As usual, if you'd like to play with the code on your own, you can download it through Cody’s Github.
Step 1: Installing and Loading Necessary Packages
Before diving into the modeling process, you must ensure that the required R packages are installed and loaded into your workspace. The two packages we'll be using are deSolve and plotly.
deSolve is a package for solving differential equations in R, which we’ll use to solve the SIR model equations.
plotly allows for creating interactive plots, which will enable us to visualize the dynamics of the SIR model effectively.
GitHub Gist
Step 2: Defining the SIR Model
The SIR model is made up of three compartments: Susceptible (S), Infected (I), and Recovered (R). Individuals transition from being susceptible to infected and then to recovered over time, modeled through a set of differential equations. Here's how to define these equations in R:
GitHub Gist
Now on first look this might be a bit strange even to experienced R users as the function seems to do very little with what we're inputting, but in reality this is because we're actually going to use this function in yet another function in Step 3. For now though, let's do a quick run-through of what we're just set up.
The function takes three arguments:
time: The current time point. While not directly used in the differential equations, it is required by the ode function from the deSolve package.
variables: A vector containing the current numbers of susceptible, infected, and recovered individuals (S, I, R).
parameters: A vector of parameters for the model, specifically beta, gamma, and N (the total population).
Within the function, we use the with function to combine
variables and parameters into a single list, which simplifies accessing these values. The with function allows us to refer to elements of the list directly by their names (e.g.,S,
I,R,
beta,gamma,
N) within its code block.
The rates of change for each compartment are then calculated according to the SIR model equations:
dS: The rate of change of susceptible individuals is the negative product of the infection rate (beta), the number of susceptible individuals (S), and the number of infected individuals (I), divided by the total population (N). This represents the number of new infections per time unit.
dI: The rate of change of infected individuals is the number of new infections (as calculated for dS) minus the number of recoveries, which is the product of the recovery rate (gamma) and the number of infected individuals (I).
dR: The rate of change of recovered individuals is simply the number of recoveries, as calculated in the dI equation.
Finally, the function returns a list containing the rates of change for each compartment, which is then used by the ode function to solve the model over time.
Step 3: Setting Initial Conditions and Parameters, Then Solving
Before solving the model, we need to specify the initial conditions (i.e., the starting numbers of susceptible, infected, and recovered individuals) and the parameters (beta and gamma) which control the disease transmission and recovery rates, respectively. Here, we start with a population of 1000 individuals, with only one infected person as the outbreak begins. The beta and gamma values are hypothetical and can be adjusted based on the disease's characteristics you're modeling. With the function we already made and initial setup ready, we can now solve the differential equations using deSolve's
ode function, which will return the solutions to every step from day 0 to day 50.
GitHub Gist
Step 4: Visualizing the Results with Plotly
Finally, to understand the dynamics of the disease through time, we'll visualize the results using plotly. This step transforms the output into a dynamic and interactive plot that can is much easier to understand, and can often wow your desired audience.
GitHub Gist
This is a fairly simply plotly graph, but it's worth noting that for each class, we need to create a separate trace for each line, which allows them to act independently of one another.
The output can be seen here:
Conclusion
Through this tutorial, you've learned how to implement and visualize the SIR model in R using deSolve and plotly. This model serves as a basic framework for understanding disease dynamics in populations, providing a foundation for more complex epidemiological modeling. It's worth noting again that the SIR model is highly simplified; It assumes no population movement, random interactions, and other factors. Later on we'll cover things like SEIR and MEM models that are a bit more complex. But for now, thanks for reading this ThuRsday Tutorial!
Humanities Moment
This ThuRsday Tutorial's featured image is An Allegory Of Water by Pauwels Franck (Flemish, 1540-1596). Pauwels Franck, also known as Paolo Fiammingo in Italy, was a Flemish painter who made a significant impact on the Venetian art scene after training in Antwerp. Active mainly in Venice, he is celebrated for his landscapes adorned with mythological, allegorical, and religious scenes, showcasing a Mannerist style influenced by notable artists like Tintoretto, Veronese, and Bassano. Though details about his early life are sparse, it's believed he was born around 1540 in Antwerp and later joined the city's Guild of Saint Luke in 1561. His journey to Italy remains largely undocumented, but by the 1560s, he was likely working in Tintoretto's workshop in Venice, where he spent the majority of his career and earned acclaim under the name Paolo Fiammingo. Franck's Venice studio attracted commissions from across Europe, including significant projects for the Fugger family, highlighting his expertise in allegorical and mythological themes. His work, which includes the celebrated Allegories of Love and various landscapes, blends Flemish precision with Venetian grace, anticipating the Italianate Flemish school.
What Are Person-Years? Understanding Person-Time in Epidemiology
Why count time instead of just people?
Imagine reading that a county program followed three residents. That head count does not tell you whether all three were observed for three years, whether one moved away after six months, or whether another developed the outcome early. Those differences change the denominator and can change the conclusion.
Person-years add the amount of time each participant was observed and at risk for the outcome. They let epidemiologists describe new cases against the time people actually contributed, rather than pretending everyone was observed for the same length of time.
One person followed for one year contributes one person-year. One person followed for six months contributes 0.5 person-years. Ten people followed for one year each contribute ten person-years. The unit can also be person-months, person-days, or person-hours when the question moves faster than a year.
Person-years
What the formula says in ordinary language
Add the time each person was observed and still able to experience the outcome. The result is time, not a number of people.
Where did person-years come from?
There is no accepted single inventor of the person-year calculation. It grew out of a longer shift in public health: instead of counting events alone, epidemiologists learned to compare events with the population being observed and the time period in which observation occurred.
John Graunt’s 1662 analysis of London’s mortality records helped establish the value of systematically describing births, deaths, and disease patterns. In the nineteenth century, William Farr expanded the use of routinely collected mortality statistics and rates for comparing populations. Their work did not produce the modern person-year formula by itself, but it helped build the measurement tradition that person-time belongs to. The CDC’s history of epidemiology describes this lineage.
The practical need for person-years became especially clear as cohort studies followed people for different lengths of time. A participant might enter late, leave early, move away, or experience the outcome before the study ends. Adding each person’s eligible follow-up creates a denominator that preserves those differences. In that sense, person-years are less a single discovery than a useful accounting language developed for studying changing populations over time. The National Academies’ reference guide describes person-years as the observation time cohort studies use to generate incidence or mortality rates.
Three neighbors, one moving van, and a denominator that changes
A county health department wants to know how quickly new asthma diagnoses are appearing among residents enrolled in a housing and health follow-up program. The program has a fixed three-year observation window, but residents do not all enroll on the same day and they may not remain observable until the window closes.
In this fictional example, three neighbors are enrolled without an asthma diagnosis. Participant B enrolls when the three-year window opens and receives a new diagnosis after three years. Participant A enrolls one year later and remains diagnosis-free through the study close, contributing two years of follow-up. Participant C enrolls when the window opens but moves out of the county after 18 months, so the program can no longer observe their outcome through its records. The numbers are invented for teaching; they are not evidence about asthma, housing, or any real community.
Participant
Follow-up time
Why observation ended
A
2.0 years
Completed available program follow-up
B
3.0 years
Received a new asthma diagnosis
C
1.5 years
Moved out of the county
Total
6.5 person-years
1 new case
Three participants contribute different amounts of observed time. Each row contributes time until the study ends, the outcome occurs, or observation stops.
Worked example
A three-year community study, three different follow-up times
Step 1: Add time, not people
2.0 + 3.0 + 1.5 = 6.5 person-years
There are three people in the study, but the denominator is 6.5 person-years because the study window, enrollment dates, and loss to follow-up give them different amounts of observed time.
Step 2: Count new cases
Participant B developed the illness during follow-up, so the numerator is 1 new case. Their time still counts up to diagnosis.
Step 3: Calculate and interpret the rate
1 / 6.5 × 100 = 15.4 per 100 person-years
About 15 new cases per 100 person-years observed.
This is a rate of occurrence over observed time. It is not a statement that 15 percent of these three people will become ill.
How do person-years become an incidence rate?
An incidence rate divides the number of new cases by the total person-time observed. That gives a rate with time in its denominator, often reported per 100, 1,000, or 100,000 person-years.
Incidence rate from person-time
What every part means
IR
Incidence rate: how often new cases arose per unit of observed time.
New cases
People who developed the outcome during follow-up. People already ill at enrollment are not new cases for this calculation.
Total person-years
The sum of the individual follow-up times in the denominator.
Multiplier
A reporting choice such as 100, 1,000, or 100,000 that makes a small rate easier to read.
What does a person-year rate mean – and not mean?
A rate of 15.4 per 100 person-years means that, in this example, one new case occurred during 6.5 person-years of observation. It describes how quickly new cases appeared in this observed group.
It does not automatically equal an individual probability or a percentage. Risk asks a different question: what proportion of a defined group develops an outcome during a stated period? A person-time rate can help estimate risk under specific assumptions, but it is not risk by itself.
A safe report sentence: “The program observed about 15 new asthma diagnoses per 100 person-years of follow-up in this fictional cohort.”
An overstatement: “Each participant had a 15% chance of developing asthma.”
The first describes an observed rate. The second treats a rate as an individual probability without the assumptions needed to do that.
Common mistakes when using person-years
Using the head count as the denominator. Three participants are not necessarily three person-years.
Counting time after the outcome. For a first-event analysis, a participant usually contributes time until the outcome occurs.
Calling a rate a probability. A rate per person-year is not automatically the chance that one person will develop the condition in one year.
Ignoring why follow-up ended. Loss to follow-up can bias results if people who leave differ meaningfully from people who remain.
Strengths and limitations
Person-time is especially helpful in cohort studies with variable follow-up. Cancer registries, vaccine-effectiveness studies, and treatment cohorts often use rates per 1,000 or 100,000 person-years because participants do not all enter, leave, or experience outcomes at the same time.
Person-years are useful accounting, not magic. If the chance of an outcome changes sharply with age, calendar time, or time since an exposure, analysts may need survival analysis or another time-to-event method that models those changes directly.
The quality of a person-time denominator also depends on whose time and outcomes the data system can see. In the fictional example, moving out of the county stops Participant C’s recorded follow-up. If residents who move are systematically different from residents who remain, the observed rate may not describe the full program population fairly. Adding person-years does not repair missing or unequal data by itself.
Knowledge check
In a second fictional county program, 80 residents enroll without the outcome of interest. Fifty-two complete two years of follow-up. Twenty move away after one year. Eight receive a new diagnosis at exactly one year. What is the total person-years, and what is the approximate incidence rate per 1,000 person-years?
132 person-years; 61 per 1,000 person-years
80 person-years; 100 per 1,000 person-years
152 person-years; 53 per 1,000 person-years
104 person-years; 77 per 1,000 person-years
Show the answer and reasoning
A is correct. The 52 workers who completed two years contribute 104 person-years. The 20 who left after one year contribute 20. The 8 diagnosed at one year contribute 8. Total: 104 + 20 + 8 = 132 person-years. The incidence rate is 8 / 132 x 1,000 = 60.6, or about 61 per 1,000 person-years. Dividing by 80 people would ignore the variable follow-up time.
Three takeaways
Person-years add observed time across participants; they are not a head count.
They make incidence rates possible when people contribute different amounts of follow-up.
A person-time rate describes the occurrence of new cases over time, not an individual probability by itself.
Conclusion
When a study follows people for unequal amounts of time, a head count alone can hide what the data actually represent. Person-years make the denominator visible: how much time was observed, for whom, and until what point. That makes rates more honest, but it does not remove the need to ask whose follow-up was missing and whether a rate is being mistaken for individual risk.
The SIR model is a mathematical sketch of how an infection moves through a population. It answers questions about direction and magnitude: does the outbreak grow or shrink? How many people might eventually be infected? What happens to the peak if the recovery rate changes? These are useful questions. They are not the same as predicting what will happen in a real outbreak.
The model assumes every person mixes randomly with every other person, that the population is constant, and that recovery produces lasting immunity. Real populations have age structure, household clusters, schools, workplaces, travel patterns, seasonal behavior, and heterogeneous contact rates. None of that is in the basic SIR model. Keep that gap visible when reading results derived from it.
The three compartments
The model sorts the entire population into three groups at any given moment. Everyone is in exactly one group, and in the basic version movement is one-directional: susceptible to infectious, and infectious to recovered.
Compartment
Symbol
Who is in it
Can they infect others?
Susceptible
S
People who have not had the infection and can catch it
No
Infectious
I
People currently infected and able to transmit
Yes
Recovered
R
People who recovered and are assumed immune
No
Every person in the model is in exactly one compartment at any moment. In the basic SIR model, movement flows one way: S to I to R.
The names are intuitive, but the recovered compartment requires a note. In the basic SIR model, ‘recovered’ also includes anyone who is no longer infectious for any reason, such as death or permanent removal from the population. The model does not distinguish between immune survivors and those who died.
Two parameters drive the outbreak
Beta (β) is the effective contact rate. Think of it as the average number of new infections one infectious person generates per day in a fully susceptible population. Beta combines two things: how often an infectious person contacts others, and the probability that any given contact transmits the infection. Public-health measures that reduce contact or transmission (masks, distancing, ventilation) aim to reduce beta.
Gamma (γ) is the recovery rate. It is the fraction of infectious people who recover per day. If the average infectious period is 10 days, gamma = 0.1 per day. The inverse of gamma (1 ÷ γ) gives you the average time someone spends in the infectious compartment.
The ratio of these two parameters, R₀ = β ÷ γ, is the basic reproduction number. R₀ answers a simple question: in a fully susceptible population, how many new cases does one infectious person produce before recovering? When R₀ is above 1, the outbreak grows. When it falls below 1, the outbreak shrinks. Getting an infectious disease’s R₀ below 1 is, in broad terms, what vaccination campaigns and control measures are trying to accomplish.
The three equations
The three SIR equations
Each equation describes how fast one compartment changes. A negative value means people are leaving; a positive value means people are arriving.
Susceptible compartment: how fast S shrinks
Susceptible people leave S when they encounter an infectious person and catch the disease. The rate of those encounters depends on how many susceptible and infectious people are mixing, divided by the total population.
Infectious compartment: how fast I grows or shrinks
The first term is the same new infections that left S. The second term removes people who recover. When new infections exceed recoveries, I grows. When recoveries outpace new infections, I falls.
Recovered compartment: how fast R grows
R grows at the same rate that I shrinks from recoveries. These three equations always balance: the total population N = S + I + R stays constant.
What every symbol means
S, I, R
The size of each compartment at a given moment. These are the variables that change over time.
N
Total population (constant in the basic SIR model: N = S + I + R at every point in time).
β (beta)
Effective contact rate. The average number of new infections one infectious person produces per unit time, given the current fraction of susceptible people. Higher beta means faster spread.
γ (gamma)
Recovery rate. The fraction of infectious people who recover per unit time. If the average infectious period is 10 days, then gamma = 0.1 per day.
d/dt
Rate of change per unit time. Each equation expresses how quickly a compartment grows or shrinks at a particular moment.
A numerical example: three steps by hand
The equations describe continuous change, but you can approximate several short steps arithmetically. The walk-through below uses clean numbers to show how the compartments shift day by day. Follow the table, then work through each step.
Day
S (susceptible)
I (infectious)
R (recovered)
New infections that day
0
999.00
1.00
0.00
—
1
998.70
1.20
0.10
0.30
2
998.34
1.44
0.22
0.36
3
997.91
1.73
0.36
0.43
Approximate compartment sizes over four days using Euler’s method. Values are rounded to two decimal places; small rounding differences accumulate across steps. S + I + R = 1,000 at every row.
Three steps by hand
Work through the first few days
Choose a small population and concrete parameter values. A basic calculator is enough for each step. This method (adding the rate to the current value at each step) is called Euler’s method. It is an approximation; real simulations use smaller time steps or more accurate solvers. The arithmetic here is meant to show how the equations behave, not to produce exact predictions.
Starting conditions
Population of 1,000 people. One person is infectious at the start. Everyone else is susceptible.
N = 1,000 S = 999 I = 1 R = 0
Parameter values:
β = 0.3 per day γ = 0.1 per day
Average infectious period: 1 ÷ 0.1 = 10 days. Basic reproduction number: R₀ = 0.3 ÷ 0.1 = 3. In a fully susceptible population, each case produces an average of 3 new cases before recovering.
Day 0 → Day 1
Plug the starting values into each equation to get the rates of change:
New infections grew from 0.30 on day 0 to 0.36 on day 1. The growth is accelerating because there are now more infectious people contributing to spread.
Day 2 → Day 3
dS/dt ≈ −0.43 dI/dt ≈ +0.29 dR/dt ≈ +0.14
S: 997.91 I: 1.73 R: 0.36
The table above shows all four days together. Each day, the number of new infections is slightly larger than the day before. This exponential-looking growth continues until the susceptible population shrinks enough that the epidemic curve begins to flatten.
What happens when R₀ is less than 1?
Change β to 0.05 with γ still at 0.1. Now R₀ = 0.05 ÷ 0.1 = 0.5. Work through day 0: dI/dt = 0.05 × 0.999 − 0.1 × 1 = 0.050 − 0.100 = −0.050. The infectious compartment shrinks immediately. A single introduced case will not grow into a sustained outbreak because each infectious person produces fewer than one new case before recovering.
How the model has been used
Public-health agencies have used SIR and related compartmental models to project how quickly an infection might spread under different scenarios, to estimate how many people might need hospital care at the peak, and to set targets for vaccination coverage. During the COVID-19 pandemic, national and regional health authorities ran variants of these models continuously to guide decisions about distancing, school closures, and vaccine rollout timing.
In those applications, the model is almost always extended beyond the basic SIR framework. SEIR models add an exposed (E) compartment for people who are infected but not yet infectious. Age-structured models replace the single homogeneous population with several age groups that have different contact rates and different outcomes. Some versions allow for waning immunity, reinfection, or multiple strains.
Even in those applications, model output is reported as a range of scenarios, not a single prediction. Small changes to beta or to the initial conditions can shift the projected peak by days or weeks. Responsible modeling teams are explicit about this uncertainty and report the assumptions that drive each scenario rather than presenting one number as the forecast.
Where the model breaks down
The homogeneous-mixing assumption is the most consequential simplification. People do not contact a random sample of the population each day. They contact household members, coworkers, classmates, neighbors. Pathogens that spread within tightly connected clusters behave differently from what a homogeneous model predicts.
The model also treats the population as constant, which fails during long outbreaks where births, deaths, and migration matter. It assumes lasting immunity after recovery, which is not true for all pathogens. And it uses fixed values for beta and gamma, even though both change over the course of a real outbreak as behavior shifts, interventions are applied, or the pathogen evolves.
Extensions of the SIR framework address many of these limits. SEIR models add an exposed compartment for people who are infected but not yet infectious. SIS models allow recovery without immunity. Age-structured and network models replace random mixing with more realistic contact patterns. Each extension adds complexity; the basic SIR model remains the starting point because it captures the essential logic of threshold dynamics with the fewest moving parts.
Knowledge check
Return to the example above: N = 1,000, I₀ = 1, β = 0.3, γ = 0.1, and R₀ = 3. Now suppose beta doubles to 0.6 because a more transmissible variant arrives. Without running a full simulation, describe two things that change and one thing that stays the same.
Show the reasoning
What changes. First, R₀ doubles from 3 to 6. Each infectious person now produces an average of 6 new cases in a fully susceptible population, so the outbreak grows faster. Second, the herd immunity threshold rises. In the original scenario, the outbreak stops accelerating once roughly 1 − 1/3 ≈ 67% of the population has been infected or immunized. With R₀ = 6, that threshold rises to 1 − 1/6 ≈ 83%. More of the population is exposed before the epidemic curve turns down. What stays the same. Gamma does not change, so the average infectious period is still 10 days. The mathematics of the equations themselves are unchanged; only the rate at which susceptibles become infectious has doubled. Running the Day 0 step with the new beta confirms the faster growth: dI/dt = 0.6 × 0.999 − 0.1 × 1 = 0.599 − 0.10 = 0.499 per day, compared to 0.20 per day before.
Humanities Moment
Edward Burne-Jones
English painter · 1833–1898
Burne-Jones was a British artist associated with the Pre-Raphaelite movement. He collaborated with William Morris on stained glass and decorative work, and his paintings often combined close observation of individual faces with mythological or allegorical subjects. Female Head Study from an Italian Model is a preparatory sketch showing that kind of attention to a single person. The painting is the article’s featured image and was sourced from Artvee by Broadly Epi.
Why this work: the SIR model strips individuals away entirely. Every person becomes a number in a compartment, flowing from one state to the next according to two rates. That abstraction is the source of the model’s usefulness and its most significant limitation at the same time. A head study is a useful counterpoint: a reminder that the compartments contain real people with different contact patterns, immune histories, and vulnerabilities that the basic equations cannot see.
Relative Risk (RR) is one of the most fundamental measures in public health, offering insights into the strength of association between an exposure (like smoking) and an outcome (such as lung cancer). Here, we'll quickly cover what Relative Risk is, and how to calculate it in Python.
Understanding the Mathematical Concept of Relative Risk
Before we delve into the Python programming, it's essential to grasp the mathematical foundation of Relative Risk. RR is a ratio that compares the probability of an event occurring in two different groups: those exposed to a certain factor versus those not exposed.
The Basic Formula
The formula for calculating Relative Risk is relatively straightforward:
Here,
Risk in Exposed Group (Re) is the probability of an event occurring in the group exposed to a certain factor.
Risk in Unexposed Group (Ru) is the probability of the same event in a group not exposed to that factor.
Now we have to ask ourselves how to calculate Re and Ru. Simply put, risk is just the number of individuals who have the condition of interest divided by all individuals who are observed.
Interpreting Relative Risk
RR = 1: Indicates no association between exposure and outcome.
RR > 1: Suggests a higher risk of the event with exposure.
RR < 1: Implies a lower risk with exposure, potentially indicating a protective factor.
Relative Risk provides a quantifiable measure to understand the strength and direction of the association, making it an invaluable tool alongside techniques like Odds Ratios.
Project Introduction
For this scenario, imagine a senior epi has called you in to figure out if there's a significant risk of developing two kinds of cancer due to smoking. They hand you a csv with 3500 entries, including smoking status and a field for diagnosis codes that looks a bit tricky. There was some talk about further data cleaning and organization but that would take days to sift through manually. No worries though, we'll get it all sorted out and the question of if there's significant risk in a matter of minutes.
Preparing the Environment: Installing and Loading Necessary Python Packages and Data
To begin, we need to set up our Python environment by installing and loading the required packages. We'll primarily be using the most popular data science package for Python,
pandas. We'll also shorten up its title to make it easier to call:
GitHub Gist
We'll also want to read in our dataset for this project, which is csv called smoking_survey.csv
GitHub Gist
Applying Functions to Data: Using .apply Function to Process Data
Now that we have our data in, we can write a quick function that makes any further data cleaning unneeded. For our purposes, the only ICD-10 codes that really matter are C34.90 or C96.29. We don't need to worry about the presence or absence of any other codes, and 1 or both of these codes would count as a case. As such, we can use fairly simple logic in Python.
GitHub Gist
Here, we first define a function called
has_lung_cancer which takes in a variable called codes . This is then compared against a list we define called lung_cancer_codes from there, we have a logic statement that if any of our codes match with our list, then we can return a value of "yes", otherwise a value of "no" is returned. We then take this function and .apply it across the dataframe we have (specifically to diagnosis_codes) to then define a new column in our dataframe called
lung_cancer.
Formatting: Selecting the Data and Data Types, Creating Contingency Tables
Now that we have our list of cases and exposures, we can get the data in a format that makes it easy to calculate our relative risk. To do this we need to take three steps. First, we need to reach into our dataframe and only pick out the columns that matter to us. Then, we need to make those columns categorical in nature, and order those categories so they are always present in a consistent manner. Lastly, we need to use the crosstab function from pandas to create a proper contingency table of our organized variables to accurate count up our exposed and positive, exposed and negative, unexposed and positive, and our unexposed and negative groups. We can do that using the following code:
GitHub Gist
Calculate Relative Risk in Python
We've finally hit the point we can properly calculate Relative Risk. For this, we turn our contingency table into a 2×2 table, then apply the .riskratio function (another name for Relative Risk) onto that preformatted table, and lastly we calculate and save the lower and upper 95% confidence intervals using this code snippet:
rr_ci_lower, rr_ci_upper = rr_table.riskratio_confint(). Let's see the rest of this code and then dig more into that line in particular as it might look a bit weird to new Python users.
GitHub Gist
So, for that tricky bit of code, here's what's going in detail, with the right side of the equation going first. What we are doing is calling a function, .riskratio_confint() on our table that returns the confidence intervals, which are formatted in a datatype called a Tuple. Tuples are a data format where multiple pieces of information are stored in sequence and can be unpacked by essentially telling Python "put the first value in this variable, then the second here" and so on. Since we're only dealing with two values, the upper and lower limits, we need only worry about those two. For the function, the lower estimate is presented first, then the upper. So, we define our variables in that order as
rr_ci_lower, rr_ci_upper.
Conclusion
To check our values, we can just print the variable names and see that the relative risk in this sample is roughly 3.85, with lower and upper bounds of 3.31 and 4.47. Since this is far and away greater than 1, as is the lower bound, we can say that there's significant risk associated with smoking when it comes to our cancers of interest.
Here, we learned what Relative Risk is, how to calculate it, and then how to prepare data and process it for Relative Risk in Python.
Humanities Moment
For this PyFriday tutorial, the featured image was Reading (ca. 1860) by Honoré Daumier (French, 1808-1879). Daumier was a prominent French artist, known for his paintings, sculptures, and printmaking. He became renowned for his critical and satirical depictions of political figures and social commentary, reflecting on France's turbulent period from the 1830 Revolution to the fall of the second Napoleonic Empire in 1870. Daumier's work, especially his caricatures published in newspapers, highlighted his strong republican democratic beliefs, often targeting the bourgeoisie, the church, and the monarchy. Despite facing imprisonment for his controversial work, including a notable piece caricaturing King Louis-Philippe, Daumier's influence extended beyond satire, as he was also a serious painter associated with realism. His artistry, which included over 100 sculptures, 500 paintings, and thousands of prints, was initially underappreciated by the public and critics, though later generations recognized him as a significant figure in 19th-century French art. Daumier's personal life was marked by financial struggles, but his legacy was cemented by his impactful contributions to political satire and art, influencing subsequent generations of artists.
Calculate relative risk in R
Introduction to Relative Risk
Relative Risk (RR) is one of the most fundamental measures in public health, offering insights into the strength of association between an exposure (like smoking) and an outcome (such as lung cancer). Here, we'll quickly cover what Relative Risk is, and how to calculate it in R.
Understanding the Mathematical Concept of Relative Risk
Before we delve into the R programming aspects, it's essential to grasp the mathematical foundation of Relative Risk. RR is a ratio that compares the probability of an event occurring in two different groups: those exposed to a certain factor versus those not exposed.
The Basic Formula
The formula for calculating Relative Risk is relatively straightforward:
Here,
Risk in Exposed Group (Re) is the probability of an event occurring in the group exposed to a certain factor.
Risk in Unexposed Group (Ru) is the probability of the same event in a group not exposed to that factor.
Now we have to ask ourselves how to calculate Re and Ru. Simply put, risk is just the number of individuals who have the condition of interest divided by all individuals who are observed.
Interpreting Relative Risk
RR = 1: Indicates no association between exposure and outcome.
RR > 1: Suggests a higher risk of the event with exposure.
RR < 1: Implies a lower risk with exposure, potentially indicating a protective factor.
Relative Risk provides a quantifiable measure to understand the strength and direction of the association, making it an invaluable tool alongside techniques like Odds Ratios.
Project Introduction
For this scenario, imagine a senior epi has called you in to figure out if there's a significant risk of developing two kinds of cancer due to smoking. They hand you a csv with 3500 entries, including smoking status and a field for diagnosis codes that looks a bit tricky. There was some talk about further data cleaning and organization but that would take days to sift through manually. No worries though, we'll get it all sorted out and the question of if there's significant risk in a matter of minutes.If you want to follow along, feel free to download the relative risk folder from Cody’s Github.
Preparing the Environment: Installing and Loading Necessary R Packages
To begin, we need to set up our R environment by installing and loading the required packages. We'll use dplyr for data manipulation and
epiR for analysis. Installing these packages is straightforward:
GitHub Gist
Data Preparation: Importing Data into R
Our analysis begins by importing the dataset into R. We'll use a practice file smoking_survey.csv file, which contains data on smoking status and various diagnosis codes for each person, age of the person and the zip-code in which they reside.
GitHub Gist
For our work, we really only need to know if the person was a smoker, and if they have a diagnosis code of interest.
Identifying the Variables: Selecting Relevant Variables for Analysis
We focus on two key variables:smoking_status and diagnosis_codes. To simplify our dataset, we'll select only these columns:
GitHub Gist
Applying Functions to Data: Using apply Function to Process Data
Next, we classify each individual's lung cancer status based on diagnosis codes. We define a function,has_lung_cancer, which returns "yes" if the codes match either of the specific lung cancer diagnoses and "no" otherwise. Then, we apply this function to our data:
GitHub Gist
From this point we can do another quick column selection to only keep what we really need. Now we can go about calculating relative risk.
Calculating Relative Risk: Manual Method
To calculate relative risk, we first create a contingency table using our selected variables:
GitHub Gist
This is done by using the table() function, where
smoking_status are our Y values, and lung_cancer status are our X values. We turned them into factors earlier on in this script to ensure the first entry is "yes" for
lung_cancer and "smoker" as the first value for smoking_status. Factors are basically organized categorical values, so R doesn't try to guess at organization and we have a messed up statistic as a result.
Then, we calculate the risk for both exposed (smokers) and unexposed (non-smokers) groups:
GitHub Gist
Let's break down the syntax of what we just did. Because we already have our data formatted into factors, we can essentially point to the location in the table instead of having clunky variable references. In these cases, those values within the brackets [X,Y] follow the system where the first value, Y is column, and the X is a row. You might notice that we have a sum() function that takes in only one argument, smoking_table[X,] . In this case we're asking R to basically take all values of that have that row location and collect them together to have an operation done on them. In this case, simply to add them all up. After creating our risk for exposed persons (
Re) and risk for unexposed persons (
Ru), and then calculate out our relative risk of ~3.85, which at first blush seems to indicate a very high risk of cancer when someone is a smoker when compared to non-smokers. But let's confirm this with a more advanced function by way of a package made for epidemiology.
Calculating Relative Risk: Using epiR
epiR simplifies this process. We can just take our table and pass it through the epi.2by2 function:
GitHub Gist
Here, we're first telling the function what data we want to use, then indicating we want to treat this as a cohort count method, and finally that our outcomes, which is to say the counts of people with and without cancer are the columns. This code not only calculates relative risk but also provides other useful statistics, including levels of significance, the Odds Ratio (which is covered in a separate article), and even confidence intervals.
Interpreting the Results: Understanding the Meaning of Relative Risk Values
The relative risk value helps us understand the likelihood of lung cancer in smokers compared to non-smokers. Values greater than 1 suggest a higher risk in the exposed group, while values less than 1 suggest a lower risk. Unsurprisingly given our scenario, our risk is far higher than 1, and using the added functionality we found in the EpiR package, we also were able to find these results to be very significant.
Conclusion
Here, we covered how to take fairly raw data, including some free-form string data, and turn it into not only a simply table but also how to calculate the relative risk in R.
Humanities Moment
The featured image for this article is Smoke Rings (1887) by Georgios Jakobides (Greek, 1853-1932). Aside from completing around 200 oil paintings which often fetched high prices at time of creation, Jakobides also created contemporary designs for currency in his native Greece.
Epi Explained: Understanding Relative Risk
Relative risk (RR), also known as risk ratio, is a cornerstone concept in epidemiology and public health, offering insight into the strength of the association between an exposure and an outcome. This Epi Explained will cover what Relative Risk is, how to calculate it, and provide some practice problems so you can check your understanding.
What is Relative Risk?
Relative risk compares the probability of a specific event (such as developing a disease) occurring in two distinct groups: those exposed to a certain risk factor versus those not exposed. It quantifies how much more (or less) likely the event is to happen in the exposed group compared to the unexposed group.
Mathematical Definition
Mathematically, relative risk is defined as the ratio of the probability of the event occurring in the exposed group to the probability of the event occurring in the unexposed group. If we denote as the probability of the event given exposure and as the probability of the event without exposure, the relative risk (RR) is given by:
Variables Explained
: Probability of the event given exposure to the risk factor.
: Probability of the event without exposure to the risk factor.
Historical Context
The concept of relative risk has roots in the 19th century when pioneering epidemiologists like John Snow used comparative analyses to understand disease outbreaks, such as cholera. Although the term and precise calculations have evolved, the fundamental idea of comparing risks to uncover associations has been central to epidemiology since its inception.
Importance in Epidemiology
Relative risk is crucial in epidemiology for several reasons:
Measuring Association Strength: RR quantifies how strongly an exposure is associated with an outcome, helping to identify potential risk factors for diseases.
Guiding Public Health Interventions: By identifying factors that significantly increase the risk of disease, public health policies can be influenced by measures such as relative risk to prevent disease in the population.
Informing Clinical Decisions: Understanding the relative risk helps clinicians advise patients on lifestyle choices, screenings, and treatments.
Calculating Relative Risk: Practice Problem
Consider a study investigating the effect of smoking on lung cancer risk. If 100 out of 1,000 smokers develop lung cancer (10%), and 30 out of 1,000 non-smokers develop lung cancer (3%), the RR of developing lung cancer for smokers compared to non-smokers is:
A. 0.03
B. 0.10
C. 3.33
D. 0.333
Answer Key, click to reveal
C.
Limitations of Relative Risk
While RR is a powerful tool, it has limitations:
Not Applicable for Case-Control Studies: RR cannot be directly calculated in case-control studies due to the retrospective nature of these studies. Odds ratios are used instead.
Can Overstate Risk: High relative risks can make associations appear stronger than they are, especially if the absolute risk is low.
Confounding Variables: RR does not account for confounding variables that may influence the observed association.
Conclusion
Relative risk provides a clear and quantifiable measure of how exposure to a certain factor alters the risk of a specific outcome. Its application in epidemiology and public health has been invaluable in understanding disease dynamics, guiding interventions, and informing clinical practice. Despite its limitations, RR remains a fundamental concept that helps distill complex relationships into actionable insights, underscoring the importance of epidemiological principles in improving public health outcomes.
Humanities Moment
The featured image for this Epi Explained is Orestes and Pylades in Tauris (1732) by
Nicolaas Verkolje (Dutch, 1673 – 1746). Verkolje was known for his classicistic style in history pieces and portraits. He was influenced by notable artists like Antoine Coypel and Gerard Dou. Verkolje was also a teacher to several artists throughout Amsterdam.
Run a t-test in Python
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 Python.
Background: Understanding T-Tests
Before we look at how to run T-Tests in Python, 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:
Sample Dependent:
Independent Samples T-Test (Two-Sample T-Test):
Purpose: Compares the means of two independent or unrelated groups.
Example: Comparing the blood pressure of patients who received two different treatments.
Paired Samples T-Test (Dependent Samples T-Test):
Purpose: Compares the means of the same group or matched pairs at two different times or under two different conditions.
Example: Measuring students’ test scores before and after a training program to assess its effectiveness.
One-Sample T-Test:
Purpose: Compares the mean of a single group against a known mean (or a theoretical value like zero).
Example: Testing if the average height of a group of individuals differs from a specific value, like the national average.
Tail Dependent:
One-Tailed T-Test:
Purpose: Tests for the possibility of the relationship in one specific direction.
Example: Testing if a new drug increases recovery rates compared to the existing standard (only looking for an increase, not a decrease).
Two-Tailed T-Test:
Purpose: Tests for the possibility of the relationship in either direction, without specifying which direction is expected.
Example: Testing if a new drug changes recovery rates (either increase or decrease) compared to the existing standard.
Assumed Variance:
Equal Variance T-Test (Pooled Variance T-Test):
Purpose: Used when the variances of the two groups are assumed to be equal.
Example: Comparing the test scores of students from two classes where the variation in scores is similar in both classes.
Unequal Variance T-Test (Welch’s T-Test):
Purpose: Used when the variances of the two groups are not assumed to be equal.
Example: Comparing the test scores of students from two schools where one school shows much greater variation in scores than the other.
Assumption of Non-Normal Distribution:
Robust T-Tests:
Purpose: Used when data do not meet the assumptions of normality. These are variations of the T-test that are less sensitive to non-normal distributions.
Example: Comparing means from data with outliers or skewed distribution.
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. The above formula is for what is called the T-Statistic. Its components are interpreted as:
: The mean of Group 1
: The mean of Group 2
: The Pooled Variance, which requires another formula we’ll cover below.
: 1/ the sample size of Group 1.
: 1/ the sample size of Group 2.
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: Where:
is the pooled variance.
is the sample size for Group 1.
is the sample size for Group 2.
is the variance for Group 1.
is the variance for Group 2.
It might be worth noting that the denominator, 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 Python, using real world data.
For our tutorial, we're only going to to install pandas, scipy and numpy. We're also going to shorten up a few names using the as command:
GitHub Gist
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. This closely resembles data you're likely to experience in the field, as it's not formatted how we'd like. Let's quickly read in the file before we get too ahead of ourselves.
GitHub Gist
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.
GitHub Gist
Now there's quite a bit to unpack from one line of code. Here, we're taking df and applying a method to it,
melt from the pandas library. Within it, we see
id_vars=['Assembly Area'] which is telling Python that we want the Assembly Areas to essentially be a key identifier for our future rows. Then, we aim to make a new column called Year which pivots those many columns for each year to rows. Lastly, we have
value_name='Count' which takes what used to be the values within the tables and sets it as a new column that is appropriately transformed so now instead of having a wide dataframe of 2 rows by 23 columns, we instead have a long one of 44 rows by 3 columns.
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.
GitHub Gist
Now that our data is properly formatted, let's get to testing.
Step 3:T-Test, The Easy Way
The easiest way to run a T-Test in Python, now that we have our data formatted, is just calling the T-Test function against our groups, like so:
GitHub Gist
For this, we're reaching into the stats library and using its standard T-Test for Independence function. From there, we're taking all values for both of our Assembly Areas, dropping any empty values from the calculation, and assuming that the variance is not equal between these two populations. Then, we can print out our values.
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.
Step 4: T-Test, 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.
GitHub Gist
Conclusion
Here, we took a look at what T-Tests are, the math underneath the term, and even how to use them in Python to answer a question about suicide rates in Northern Ireland.
Humanities Moment
This tutorials featured image is Sunset in Ireland (1863) by Francis Seymour Haden (English, 1818-1910). Haden, a surgeon by profession, also helped revitalized the practice of etching in the English art scene. He was also an avid collector of Rembrandt, and a president of the Society of Royal Printmakers in London.
Cookie Consent
We use cookies to improve your experience on our site, and of course serve ads to keep this otherwise free service running.
Websites store cookies to enhance functionality and personalise your experience. You can manage your preferences, but blocking some cookies may impact site performance and services.
Essential cookies enable basic functions and are necessary for the proper function of the website.
Name
Description
Duration
Cookie Preferences
This cookie is used to store the user's cookie consent preferences.