For this ThuRsday Tutorial, we're going to cover something a bit different. Instead of showing how to do fairly simple epidemiological calculations, this edition will cover the first of many Machine Learning and Artificial Intelligence topics: Decision Trees. First, we're going to cover what Decision Trees are, then do a quick step by step implementation guide in R, and lastly, leave you with a bit of homework should you wish. As usual, if you want to follow along, head over to Cody’s Github to download the article code and data.
What is a Decision Tree?
A decision tree is a type of supervised learning algorithm used for classification and regression tasks. To newcomers that previous sentence may have made very little sense, so let's break this down. A supervising learning algorithm is a machine learning method that uses data that has at least in part already been reviewed by a human, so the algorithm can learn through reviewing previously tagged data, and test itself against similarly tagged data.Classification is the sorting of data into specific categories (for example, petting pictures of cats and dogs in a "pets" category, while pictures of flowers and trees may be put in a "plants" category), and Regression is a way to estimate future numerical data based on patterns seen in previous numerical data.
A decision tree operates much like the process you might use to make a decision in everyday life—by asking a series of yes/no questions until a conclusion is reached. In the context of machine learning, these questions are based on data and are structured in a tree-like model of decisions.
The Structure of a Decision Tree
Nodes: Each point in the tree where a question is asked is called a node. The very first question, which starts the decision-making process, is known as the root node. From this point, the tree branches out based on possible answers to the questions posed.
Branches: Each answer to a question leads to a new branch in the tree. These branches represent the flow from one question to another, guiding the process through more specific inquiries until a final decision can be made.
Leaves: The leaves of the tree are the end points, representing the outcomes or final decisions. Once a leaf is reached, no further questions are necessary, and the decision tree has provided its prediction or classification based on the inputs given.
Decision trees are built using algorithms that identify the most significant questions to ask at each step. The goal is to select questions that best split the data into distinct categories, making it easier to predict or classify the data as you move deeper into the tree. This process involves statistical methods that measure how well each question separates the data according to the target variable (the outcome we want to predict).
In technical terms, the algorithm selects the questions based on measures like Gini impurity or entropy, which quantify how much uncertainty or "messiness" exists in the categories formed at each step. By choosing questions that reduce this uncertainty the most, the decision tree can efficiently reach accurate decisions.
One practical example of how one could imagine a decision tree is imagining having to sift through hospital visit data to find potential cases of the flu. Say that you know from previous experience what all the symptoms and test results may need to be to be certain of a flu diagnosis (the training section), and you're given a few records to skim through. You'd likely use a system of yes or no questions, arranged by relative relevance to sort these records.
Does the record indicate a positive flu test? If so, then we can say it's a flu record, if not, it may not be the flu, and if we don't have results, we can move down a branch and onto the next node. Does the record indicate fever, aches, or have had recent contact with someone already sick with the flu? Depending on the answer we can use the algorithm to not only have a good idea of which records are flu or not, but also have a standard path to explain our decisions easily.
Now that we have a basic idea of how Decision Trees work, let's try building one in R.
Building a Decision Tree in R
Project Outline
for this scenario, imagine you've been contacted to take a look at some healthcare expenditure data, and to fill in some potentially missing data so that other programs might be able to better estimate the benefits of prevention programs for various conditions prior to surgical intervention in terms of patients seen for said procedures. For this, we'll be using data from the Health Service Executive , sourced from Open EU Datasets Portal. For this tutorial, the data is also included in the Github repository where the tutorial code is also found. This dataset shows various surgical procedures for the last 20 years or so, how many of these procedures were performed each year, and if there was a break in the reporting series for the year being reported on. By nature of the data, the decision tree will be very simple, and while such a simple use case may not be ideal for this task, the limited variables make it easier to see how these work. In general, you'd want data with more variables that could help explain potential relationships between key factors.
Setting Up in R: Libraries
First, ensure you have the necessary packages installed and loaded. We will use `readr` for data loading, `caret` for data partitioning, and `rpart` for creating the decision tree models.
GitHub Gist
Data Read-In
We start by loading our dataset and examining its structure. This step helps us understand the types of variables and data formats we are dealing with.
GitHub Gist
Here, we can see that we're dealing with character and numerical variables, which is fine to start with. But to be able to make our Decision Tree work out, we'll need to change a few of these data types around a bit.
Data Preparation
Converting character variables to factors is crucial because many modeling techniques, including decision trees, handle factors differently from other data types. Namely, given that factor data is organized into distinct categories, it can help our Decision Tree organize the questions and answers into a proper tree. Here, we will want to see how the Year , Type of Surgical Procedure and Case Type influence our Value variable, so let's go ahead and change those to factors.
GitHub Gist
We also split the data into two subsets based on a flag indicating a break in series, where those with breaks are going to be serving as our implementation dataset, while the rest will be used for training and testing.
GitHub Gist
Creating Training and Testing Data
For training our model, we create a stratified sample to ensure each category of the surgical procedure is fairly represented in both training and testing sets.
GitHub Gist
Here we are setting a random seed to pick out what records are retained in training or testing, then breaking the data up based on surgical procedure as mentioned earlier, and creating a 70-30 split for training and testing respectively. We then break those sets up for later use.
Building and Evaluating the Decision Tree Model
We now build our decision tree model using the `rpart` function.
GitHub Gist
Within `rpart`, we set up an equation of sorts for the Decision Tree to work with where our Value variable is considered to be determined by a mix of our factored variables, where we can train on our predetermined data, and are using ANOVA regression tree models specifically.
Next we can also take a look at how well it's handled the training data so far, either through various statistical measures using the summary function, or by visually inspecting the resulting tree using both plot for the basic shape, and text to show the variables and associated potential choices and weight.
Even at this point we can see that the Mean Squared Error is very large, and can fairly comfortably be certain this method is less than ideal for this question, but we can still see how it performs against the testing dataset, and go from there.
GitHub Gist
Improving the Decision Tree
These initial results are not great to say the least, so we might consider several strategies:
–Cross-validation: Helps in understanding how the model performs across different subsets of the data, and can improve results with that understanding.
–Parameter tuning: Adjusting the complexity of the model might help reduce overfitting or underfitting. As a quick note, overfitting refers to when a model can do extremely well on training data, but when introduced to new data which don't match the exact trends and patterns, tend to fail. Underfitting basically means a generally under-performing model both with training and other data.
GitHub Gist
With the above script we edit our model call slightly, using a slightly different method and then doing a 10x cross validation. We can then print the results of this validation and get a cp value for the best model. This cp value can then be used to control the specifics of the model and be ran instead of the base model.
We can then go over what we've previously done, and finally implement a model on our missing data.Given the data isn't truly missing, we can look at the Predicted Value and examine it against our actual Value to see how well this model did in both base performance and how the model can explain data relationships.
GitHub Gist
Conclusion: Next Steps and Future Improvements
Based on the performance and the nature of data, we could consider:
– Including more relevant features that might influence the outcomes.
– Trying different types of models that may fair better for this question (Regression models, XGBoost, etc).
– Revisiting data preprocessing steps to handle outliers, missing values, or transform variables.
– If possible, changing the question to see if end values can be categorical instead of numerical (so under 5000, between 5000-10000, etc), which tends to perform better in tree models.
Feel free to try your hand at improving performance, and use it as a bit of a testing ground. It's worth noting that with a lot of Machine Learning methods, practicing how and when to implement them is crucial to having a good understanding of methods and their steps.
Humanities Moment
The featured image for this ThuRsday Article is September – The Parable of the Barren Fig Tree (1611) by Abel Grimmer (Flemish, c. 1570–c. 1620). Grimmer was a Flemish late Renaissance painter from Antwerp, known for his landscape paintings and architectural scenes that displayed a trend towards naturalism. Influenced heavily by his father, Jacob Grimmer, and artists like Pieter Bruegel the Elder, Abel developed a style characterized by simplified, schematic compositions with vivid color harmonies, which allowed him to produce work efficiently and affordably for the Antwerp market.
Clinical trials, particularly randomized controlled trials (RCTs), are critical to evidence-based interventions, pharmaceutical testing, and public heatlh. They provide the most reliable data on the effectiveness of treatments, interventions, and preventive strategies. This Epi Explained delves into the essence of clinical trials, with a focus on RCTs, explaining their purpose, structure, and significance in medical research.
Introduction to Clinical Trials
Clinical trials are research studies performed on people to evaluate medical, surgical, or behavioral interventions. They are the primary method researchers use to determine if a new treatment, like a new drug, diet, or medical device (e.g., a pacemaker), is safe and effective in humans. Before a new treatment is tried with human patients, it undergoes extensive preclinical research in labs, often involving animal testing and almost without exception, review by an Institutional Review Board to assure the testing is ethical and appropriate.
What Sets Randomized Controlled Trials Apart?
Randomized Controlled Trials (RCTs) are considered the gold standard in clinical research. They are characterized by the random allocation of participants into either the experimental group receiving the treatment under investigation or the control group receiving the treatment that’s being tested, or a placebo (or in the cases of comparing against a standard treatment, that may take the place of placebo or be alongside it). This randomization helps ensure that the treatment and control groups are as similar as possible at the start of the trial, thereby isolating the effect of the treatment from other factors.
Key Components of RCTs:
Randomization: This process eliminates selection bias, balancing both known and unknown prognostic factors, in the assignment of treatments to participants.
Control Group: The standard against which the new treatment is compared. It can be a placebo (an inactive substance that looks like the treatment), or a standard treatment.
Blinding: To prevent the placebo effect and observer bias, RCTs often employ blinding. Single-blind means the participant doesn’t know which group they’re in, while double-blind means neither the participants nor the researchers know who’s receiving the treatment or the placebo.
The Phases of Clinical Trials
Clinical trials are conducted in phases, each with a specific purpose:
Phase I: Tests a new treatment on a small group of people (20–80) for the first time to evaluate its safety, determine a safe dosage range, and identify side effects (if applicable).
Phase II: The treatment is given to a larger group of people (100–300) to see if it is effective and to further evaluate its safety.
Phase III: Administered to even larger groups (1,000–3,000) to confirm its effectiveness, monitor side effects, compare it to commonly used treatments, and collect information that will allow the treatment to be used safely.
Phase IV: Conducted after the treatment has been marketed to gather information on its effect in various populations and any side effects associated with long-term use.
It should be noted that these phases are general guidelines and depending on specific intervention, the groupings may change.
Importance of RCTs in Medical Research and Public Health
RCTs are pivotal in advancing medical knowledge, patient care, and public health for several reasons:
Efficacy and Safety: They provide the strongest evidence on the efficacy and safety of new treatments, helping to inform clinical guidelines and policy decisions.
Regulatory Approval: Data from RCTs are essential for the approval of new treatments by regulatory bodies like the FDA in the United States.
Understanding Treatment Effects: RCTs help understand the size of the effect of new treatments and who is most likely to benefit from them.
Challenges and Considerations
While RCTs are the gold standard, they also face several challenges:
Ethical Concerns: Ensuring the ethical treatment of participants, especially in trials involving vulnerable populations or life-threatening conditions, is paramount.
Cost and Time: RCTs are expensive and time-consuming to conduct, which can limit the availability of evidence for new treatments.
Generalizability: The strict criteria for trial participants can sometimes limit the applicability of the findings to the general population.
Real-World Application
An example of an impactful RCT is the trial that established the efficacy of antiretroviral therapy (ART) for HIV/AIDS in the 1990s. This trial provided conclusive evidence that ART could significantly reduce the viral load in patients with HIV, transforming HIV from a fatal diagnosis into a manageable chronic condition.
Conclusion
Randomized controlled trials are a critical component of clinical research, offering the most reliable evidence on the safety and efficacy of new treatments. While they come with challenges, the benefits of RCTs in advancing medical science and improving patient or community outcomes are undeniable. Understanding the basics of RCTs helps demystify an essential process in the development of interventions and highlights the importance of rigorous scientific research in health, whether it be at a patient or societal level.
Humanities Moment
The featured image for this Epi Explained is Blind Fiddler (1812) by
John Lewis Krimmel (American, 1786-1821). often referred to as “the American Hogarth,” Krimmel was a pioneering American genre painter who, after emigrating from Germany to Philadelphia in 1809, vividly captured everyday life and social scenes, such as Fourth of July celebrations and election days. Krimmel, who tragically died at 35, significantly influenced later American artists like William Sidney Mount and Thomas Eakins, and was notable for being one of the first to depict free African Americans in his works.
Epi Explained: Understanding Case-Control Study Design
Case-control studies are a cornerstone of population research, offering insights into the factors that may contribute to the occurrence of diseases or conditions. These studies are particularly invaluable in understanding rare diseases or outcomes that take a long time to develop. This Epi Explained provides a detailed overview of case-control studies, including their design, advantages, disadvantages, and real-world applications.
Introduction to Case-Control Studies
At its core, a case-control study is a type of observational study where two groups of individuals are selected based on the presence (cases) or absence (controls) of a particular disease or outcome. Researchers then look backward in time to assess the exposure to suspected risk factors or interventions among these two groups. The objective is to determine if there is an association between the exposure and the disease by comparing the exposure rates between cases and controls.
Key Variables in Case-Control Studies
Cases: Individuals who have the disease or outcome of interest.
Controls: Individuals who do not have the disease or outcome of interest.
Exposure: The factor(s) being investigated as a potential cause of or association with the disease or outcome.
Designing a Case-Control Study
The design phase of a case-control study is critical for ensuring its validity and reliability. Here’s a breakdown of the essential steps:
Selection of Cases and Controls
Cases are typically selected based on specific diagnostic criteria to ensure that they indeed have the disease or outcome of interest.
Controls should be as similar as possible to cases but without the disease or outcome. They can be drawn from the same community or hospital, depending on the study design.
Assessment of Exposure
Exposure information is usually collected through interviews, medical records, or questionnaires. It’s crucial that the assessment of exposure is conducted without knowing the case or control status of the participants to reduce bias.
Matching
Matching is a technique used to control for confounding variables by selecting controls that are similar to cases in terms of certain key characteristics (e.g., age, gender, or other factors not under study).
Advantages of Case-Control Studies
Efficiency: Particularly useful for studying rare diseases or diseases with a long latency period since they start with the outcome and require fewer subjects.
Cost-effectiveness: Less expensive and quicker to complete than cohort studies or randomized controlled trials, especially when the outcome is rare.
Feasibility: Can investigate multiple exposures or risk factors for a single disease.
Disadvantages of Case-Control Studies
Temporal ambiguity: It can be difficult to determine whether the exposure preceded the disease (cause and effect) due to the retrospective nature.
Selection bias: Improper selection of cases and controls can lead to biased results.
Recall bias: Cases may remember their exposures more clearly or differently than controls, affecting the reliability of the findings.
Calculating Odds Ratios
One of the key statistical tools used in case-control studies is the odds ratio (OR), which measures the odds of exposure among cases relative to the odds of exposure among controls. The formula for calculating the odds ratio, as well as a full breakdown of what Odds Ratios can be seen in an earlier Epi Explained, or if you’d like, we also have how to do ORs in R and Python as well.
Real-World Applications
Case-control studies have been instrumental in identifying risk factors for various diseases. For instance, the landmark British Doctors Study, which was a case-control study, established the link between smoking and lung cancer. Such studies continue to be crucial in public health research, guiding preventive measures and policy decisions.
Conclusion
Case-control studies are a vital part of the public health toolkit, enabling researchers to identify and understand the risk factors for diseases or conditions. Despite their limitations, when designed and conducted properly, they provide valuable insights that can inform public health strategies and medical guidelines.
By grasping the fundamentals of case-control studies, including their design, execution, and analysis, we can better appreciate the challenges and rewards of uncovering the factors that influence health and disease across populations.
Humanities Moment
The featured image for this Epi Explained is “Alarming Case of Indigestion: The Doctor Called In” (1847) by John Doyle (Irish, 1797 – 1868). John Doyle, better known by his pen name H.B., was an influential Irish political cartoonist and caricaturist who gained recognition in the early 19th century. He initially trained as a painter, notably producing equestrian portraits and landscapes before transitioning to political cartoons in 1827. Doyle’s work, characterized by subtle humor and accurate depictions, was widely popular in his time, and he played a crucial role in the foundation of British cartoon satire, influencing the style later epitomized by publications like Punch magazine. Despite his success during his lifetime, his reputation declined posthumously, although he left a significant legacy, including influencing his grandson, Sir Arthur Conan Doyle.
Epi Explained: Understanding Community Trials
Nonrandomized (Community) Trials, also known as observational studies or quasi-experimental studies, are a crucial research design in epidemiology and public health. These studies provide valuable insights into the effects of interventions and exposures when randomization is not feasible due to ethical, practical, or logistical reasons. This entry of Epi Explained offers a comprehensive exploration of nonrandomized community trials, emphasizing their design, advantages, and limitations.
Introduction to Nonrandomized Trials
Nonrandomized trials assess the impact of interventions or exposures without the random assignment of participants to intervention or control groups. Instead, these studies rely on existing group allocations or allow participants to choose their intervention status, leading to a comparison between naturally occurring or self-selected groups.
Key Features
Observational Nature: Researchers observe outcomes without manipulating the study environment.
Quasi-Experimental Design: These trials attempt to infer causality from interventions in the absence of randomization.
Community-Based: Often conducted at the community level, addressing public health interventions.
Design of Nonrandomized Trials / Community Trials
Nonrandomized trials vary widely in design, but they share common elements aimed at minimizing bias and establishing a causal link between the intervention and the outcome. Often though, Community Trials are used to evaluate interventions that would otherwise be hard to track in a clinical or academic environment, such as ad campaigns or social media movements used to inform or improve health choices within communities.
Selection of Participants
Participants are selected based on their exposure status, decision to participate in an intervention, or by demographic or regional catchment. In general, one must carefully document the criteria for inclusion and exclusion to ensure clarity and reproducibility.
Comparison Groups
Although not randomly assigned, comparison groups in nonrandomized trials are essential for evaluating the intervention’s effectiveness. Researchers use various methods to create or identify these groups, such as matching or using a Welch’s T-Test on the resultant data to estimate effectiveness.
Outcome Measurement
Outcomes are measured uniformly across all participants, regardless of their group. This standardization is critical for the validity of the study’s findings.
Statistical Analysis
Statistical methods play a vital role in adjusting for confounding variables and biases inherent in nonrandomized designs. Techniques such as propensity score matching and regression analysis help to approximate the conditions of a randomized trial.
Advantages of Nonrandomized / Community Trials
Feasibility: Ideal in situations where true randomization is not possible or ethical, either by time or design.
Real-World Application: Can be performed within a community as opposed to in a strictly controlled setting.
Cost-Effectiveness: Generally less expensive and faster to conduct than randomized controlled trials (RCTs).
Limitations and Challenges
Confounding Variables: The lack of randomization can lead to imbalances in baseline characteristics, affecting the study’s internal validity.
Bias: Selection bias, information bias, and confounding are more challenging to control.
Causal Inference: Establishing causality is more complex, requiring careful interpretation and robust statistical methods.
Example of a Community Trial
Though there are many Community Trial examples that have been put into practice, perhaps the most famous use was to prove the value of water fluoridation in terms of combating tooth decay, where two towns in New York were chosen as experiment sites; One which had Fluoride added to water, another whose water was left untreated. The full study, design, and results are available through the American Journal of Public Health.
Practice Problem
Consider a public health researcher investigating the impact of a community-based exercise program on reducing the incidence of type 2 diabetes. Due to the nature of the intervention, participants cannot be randomly assigned to the exercise program or a control group. Instead, the study compares outcomes between those who voluntarily join the program and those who do not, adjusting for factors like age and family history of diabetes.
Question: What is a key characteristic that distinguishes nonrandomized trials, such as the one described above, from randomized controlled trials (RCTs)?
A. Nonrandomized trials primarily focus on rare diseases for which large sample sizes are not required.
B. In nonrandomized trials, the researcher actively assigns participants to intervention or control groups based on their preferences.
C. Nonrandomized trials often involve comparisons between groups that are not equivalent at baseline, requiring statistical adjustments to estimate the intervention’s effect.
D. The outcomes of interest in nonrandomized trials are usually subjective, relying heavily on participant self-reporting.
Answer: Click to reveal
C. Nonrandomized trials often involve comparisons between groups that are not equivalent at baseline, requiring statistical adjustments to estimate the intervention’s effect. This key characteristic highlights the importance of carefully considering and controlling for potential confounders to draw valid conclusions about the intervention’s efficacy.
Conclusion
Nonrandomized (Community) Trials offer a vital alternative to randomized controlled trials, especially in contexts where randomization is not practical or ethical. While they come with certain limitations and challenges, particularly regarding bias and confounding, their real-world applicability and cost-effectiveness make them an indispensable tool in public health research. By employing rigorous design and analytical techniques, researchers can leverage these studies to generate valuable insights into the effects of public health interventions and policies.
Humanities Moment
The featured image for this entry in Epi Explained is Country Life Stories: Some Rural Community Helpers page illustration 11 (1938) by Vernon Winslow (American, 20th Century). Not much is recorded about Vernon Winslow, who illustrated a series of images for the book Country Life Stories: Some Rural Community Helpers. This book was primarily aimed at rural schoolchildren as reading practice, but was also a great showcase of African American communities written by an African American woman, Helen Whiting. The illustrations of this book often show neighbors and other community members helping each other out in various circumstances.
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 PyFriday 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 PyFriday 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 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 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 Python:
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 odeint function from the scipy 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 odeint function to solve the model over time.
Step 3: Initial Conditions, Parameters, and 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
scipy's odeint function, which will return the solutions to every step from day 0 to day 50.
GitHub Gist
Step 4: Visualizing the Outcome 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.
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 SEIR model using Python, showcasing the model's utility in understanding infectious disease dynamics. 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 PyFriday Tutorial's featured image is The Fortune-teller (1857) by Adolph Tidemand (Norwegian, 1814-1876).Adolph Tidemand was a Norwegian romantic nationalism painter known for works like "The Haugeans" and "The Bridal Procession in Hardanger," painted in collaboration with Hans Gude. He studied in Copenhagen and Düsseldorf, where he developed his style influenced by Norwegian history, eventually becoming renowned for his depictions of Norwegian farm life, contributing to the elevation of peasant culture in art.
Build an SEIR model in R
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.
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.