First onsets of mania, schizophrenia spectrum disorders, and major depressive disorder in the perimenopause

Lisa M. Shitomi-Jones, Clare Dolman, Ian Jones, George Kirov, Valentina Escott-Price, Sophie E. Legge, Arianna Di Florio


The following code was developed to investigate first onsets of psychiatric disorders during the perimenopause.
This document is a companion to the manuscript published in Nature Mental Health.


This code is covered by the GNU GPLv3 license. Please see the License tab for full information.
© Copyright 2024 Cardiff University. All rights reserved.

Data preparation

Data preparation

Please note that, due to the processing time of the data preparation script, this is run separately from the code in all other tabs. This is run as an R script (not as an Rmd), thus the code presented here is not run within this markdown document, but is presented here for transparency.

Data preparation includes the following:

  1. Settings (initial set up)
  2. Load data
  3. Inclusion criteria
  4. Diagnosis and onset age extraction


1. Settings

Initial set up. Includes the following:

  • Specifying paths to data directories
  • Specifying input file names
  • Storing UK Biobank codes as variables (for readability)
# 1. SETTINGS ---------------------------------------------------------------------------------------------------
# Load packages
library(tidyverse)                          # Packages for data wrangling

## DIRECTORIES
DATA_DIR  <- "~/Perimenopause/Data"         # Data directory
PLOT_DIR  <- "~/Perimenopause/Plots"        # Output directories for plots to be saved
# Diagnoses extraction directories 
MENO_DIR  <- DATA_DIR                       # Menopause-only, all column version of UKBB (path)
CODE_DIR  <- paste0(DATA_DIR, "/Diagnoses") # Diagnoses codes directory path

## FILE NAMES
UKBB_FIL  <- "/UKBB_menopause.tab"          # UKBB data file name (post column extraction)
UKBB_OCC  <- "/firstoccurrences.txt"        # UKBB first occurrences data file name (post column extraction)
UKBB_OPR  <- "/operations.txt"              # UKBB operations file name (post column extraction)
# Diagnoses extraction file names
MENO_FIL  <- "/menopauseonly_allcols.csv"   # Menopause-only, all column version of UKBB (file name)
SCOD_FIL  <- "/search_codes_severe_dep.csv" # Search codes file for severe depression diagnoses criteria

## CODES (data field IDs and illness codes)
# Variables with only one value
ID        <- "f.eid"                        # Individual ID
SEX       <- "f.31.0.0"                     # Sex
YOB       <- "f.34.0.0"                     # Year of birth
MHQ_D_AGE <- "f.20433.0.0"                  # Age at first episode of depression (MHQ)
MHQ_P_AGE <- "f.20461.0.0"                  # Age when first had unusual or psychotic experience (MHQ)
MHQ_DATE  <- "f.20400.0.0"                  # Date of completing mental health questionnaire
MHQ_MD_C1 <- "f.20446.0.0"                  # Mental health questionnaire, major depression cardinal symptom 1
MHQ_MD_C2 <- "f.20441.0.0"                  # Mental health questionnaire, major depression cardinal symptom 2
MHQ_MD_S1 <- "f.20536.0.0"                  # Mental health questionnaire, major depression symptom 1
MHQ_MD_S2 <- "f.20532.0.0"                  # Mental health questionnaire, major depression symptom 2
MHQ_MD_S3 <- "f.20449.0.0"                  # Mental health questionnaire, major depression symptom 3
MHQ_MD_S4 <- "f.20450.0.0"                  # Mental health questionnaire, major depression symptom 4
MHQ_MD_S5 <- "f.20435.0.0"                  # Mental health questionnaire, major depression symptom 5
MHQ_MD_S6 <- "f.20437.0.0"                  # Mental health questionnaire, major depression symptom 6
MHQ_MD_I  <- "f.20440.0.0"                  # Mental health questionnaire, major depression impact
MHQ_MD_L  <- "f.20442.0.0"                  # Mental health questionnaire, major depression lifetime
BIPOLAR   <- "f.20126.0.0"                  # Bipolar and major depression status
TOWNSEND  <- "f.189.0.0"                    # Townsend deprivation index at recruitment
# Variables with multiple values (from one measure)
MHQ_STAT  <- "f.20544."                     # Mental health problems ever diagnosed by a professional (MHQ)
OPR_CODE  <- "f.41272."                     # Operative procedures - OPCS4
# Variables with multiple values (from repeat measures)
ASCE_DATE <- "f.53."                        # Date of attending assessment center
ASCE_AGE  <- "f.21003."                     # Age when attended assessment center
ETHNICITY <- "f.21000."                     # Ethnic background
BMI       <- "f.21001."                     # Body mass index (BMI)
SMOKE_STAT<- "f.20116."                     # Smoking status
ALC_FREQ  <- "f.1558."                      # Alcohol intake frequency
HAD_MENO  <- "f.2724."                      # Had menopause
AGE_MENO  <- "f.3581."                      # Age at menopause (last menstrual period)
HYSTEREC  <- "f.3591."                      # Ever had hysterectomy (womb removed)
BILAT_OP  <- "f.2834."                      # Bilateral oophorectomy (both ovaries removed)
PILL_START<- "f.2794."                      # Age started oral contraceptive pill
SR_I      <- "f.20002."                     # Non-cancer illness code, self-reported
MED_CODE  <- "f.20003."                     # Treatment/medication code
SR_I_AGE  <- "f.20009."                     # Interpolated age of participant when illness first diagnosed
SR_AGE    <- "f.21003."                     # Age when attended assessment center
DEP_GP    <- "f.2090."                      # Seen doctor (GP) for nerves, anxiety, tension or depression
DEP_PSY   <- "f.2100."                      # Seen a psychiatrist for nerves, anxiety, tension or depression
# Illness codes for self-report/assessment center (field ID 20002)
dp        <- 1286                           # Depression
sz        <- 1289                           # Schizophrenia
bp        <- 1291                           # Mania/bipolar disorder/manic depression
an        <- 1287                           # Anxiety/panic attacks
nb        <- 1288                           # Nervous breakdown
ptsd      <- 1469                           # Post-traumatic stress disorder    
ed        <- 1470                           # Anorexia/bulimia/other eating disorder
stress    <- 1614                           # Stress
ocd       <- 1615                           # Obsessive compulsive disorder (OCD)
insom     <- 1616                           # Insomnia 
sub_alc   <- 1408                           # Alcohol dependency
sub_opi   <- 1409                           # Opioid dependency
sub_oth   <- 1410                           # Other substance abuse/dependency
# List of self-report illness codes
sr_illnesses <- list(dp = dp, sz = sz, bp = bp, an = an, nb = nb,
                     ptsd = ptsd, ed = ed, stress = stress, ocd = ocd, insom = insom,
                     sub_alc = sub_alc, sub_opi = sub_opi, sub_oth = sub_oth) 
# Illness codes for MHQ diagnoses (field ID 20544)
mhq_sz    <- 2                              # Schizophrenia
mhq_ps    <- 3                              # Any other type of psychosis or psychotic illness
# List of MHQ illness codes
mhq_illnesses <- list(mhq_sz = mhq_sz, mhq_ps = mhq_ps) 
# List of all illness codes
all_illnesses <- c(sr_illnesses, mhq_illnesses, psychosis = NA, substanceabuse = NA)


2. Load data

Loads packages and read in UK Biobank data.

# 2. LOAD DATA --------------------------------------------------------------------------------------------------
# Read in UKBB data
UKBB_all <- read.delim2(paste0(DATA_DIR, UKBB_FIL))
UKBB_occ <- read.delim2(paste0(DATA_DIR, UKBB_OCC))
UKBB_opr <- read.delim2(paste0(DATA_DIR, UKBB_OPR))

# Rename column names for merging
names(UKBB_occ) <- sub("^X", "f.", names(UKBB_occ))
names(UKBB_opr) <- sub("^X", "f.", names(UKBB_opr))
names(UKBB_occ)[names(UKBB_occ) == "eid"] <- "f.eid"
names(UKBB_opr)[names(UKBB_opr) == "eid"] <- "f.eid"

# Merge
UKBB_all <- left_join(UKBB_all, UKBB_occ, by = "f.eid")
UKBB_all <- left_join(UKBB_all, UKBB_opr, by = "f.eid")

# Remove participants who have withdrawn from the study
remove_ids <- read.delim2(paste0(DATA_DIR, "/w13310_2023-04-25.csv"))
remove_ids <- as.vector(t(remove_ids))
UKBB_all   <- UKBB_all[!UKBB_all$f.eid %in% remove_ids, ]

# Count sample size and execute print statement
n_UKBB <- nrow(UKBB_all)
noquote(paste0("Total number of individuals in UK Biobank dataset: ", n_UKBB))


3. Inclusion criteria

Restricts to individuals who:

  • Reported female sex
  • Have reported occurrence of menopause
  • Did not change from “yes” to “no” for the “had menopause” variable across successive visits
  • Did not report ages at menopause which varied by more than 2 years
  • Reported age at menopause over 40 years
  • Did not report a hysterectomy and/or bilateral oophorectomy
  • Do not have hospital inpatient records for a uterine ablation (or similar)
  • Do not have the mirena coil
  • Did not start taking a contraceptive pill at the age they reported menopause
# 3. INCLUSION CRITERIA -----------------------------------------------------------------------------------------
## Restrict to female participants (coded as 0)
UKBBv1 <- subset(UKBB_all, get(SEX) == 0)
# Count sample size and execute print statements
n_females <- nrow(UKBBv1)
noquote(paste0("Number of individuals removed based on sex: ", n_UKBB - n_females))
noquote(paste0("Sample size following restriction to females: ", n_females))

## Restrict to individuals who reported menopause at any measurement
meno_cols <- grep(HAD_MENO, names(UKBBv1)) # Find columns for "had menopause" variable
UKBBv2 <- UKBBv1 %>% filter_at(vars(all_of(meno_cols)), any_vars(. == 1)) # Checks menopause columns for any that are equal to 1 (1="Yes")
# Count sample size and execute print statements
n_menopause <- nrow(UKBBv2)
noquote(paste0("Number of individuals removed based on menopause occurrence: ", n_females - n_menopause))
noquote(paste0("Sample size following restriction to menopause occurrence: ", n_menopause))

## Restrict to those who did not change from 'yes' (had menopause) to 'no' (no menopause)
# Menopause answer variables
meno0 <- paste0(HAD_MENO, "0.0")
meno1 <- paste0(HAD_MENO, "1.0")
meno2 <- paste0(HAD_MENO, "2.0")
# Yes at first visit, then no at any other visit
discrep1 <- subset(UKBBv2, get(meno0) == 1 & (get(meno1) == 0 | get(meno2) == 0))
# No/unknown at first visit, yes at second visit, then no at third visit
discrep2 <- subset(UKBBv2, get(meno0) != 1 & get(meno1) == 1 & get(meno2) == 0)
# Combined menopause discrepancies
discrep <- rbind(discrep1, discrep2)
# Remove discrepancies from menopause subset
UKBBv3 <- UKBBv2[!(UKBBv2[,ID] %in% discrep[,ID]),]
# Count sample size and execute print statements
n_fmp_inconsistent <- nrow(discrep)
n_UKBBv3 <- nrow(UKBBv3)
n_multiple_FMPstatus <- sum(rowSums(!is.na(UKBBv1[c(meno0, meno1, meno2)])) >= 2)
noquote(paste0("Number of individuals with reversed menopause status (yes to no): ", n_fmp_inconsistent))
noquote(paste0("Sample size following restriction to consistent menopause status: ", n_UKBBv3))
noquote(paste0("Number of participants who answered menopause status question more than once: ", n_multiple_FMPstatus))

## Filter to those that did not report ages at menopause which varied by more than 2 years
# Create subset with only columns of interest (ID and age at menopause)
fmp_age_df <- UKBBv3 %>% select(contains(c(ID, AGE_MENO)))
# Code "do not know" and "prefer not to answer" as NA (-1 = Do not know; -3 = Prefer not to answer)
fmp_age_df[fmp_age_df<0] <- NA
# Create empty vectors
fmp_age_range    <- c()  # Difference between largest and smallest reported age at menopause
problem_eids     <- c()  # IDs of individuals to remove
# Loop through rows to find inconsistent values for age at FMP
for (row in 1:nrow(fmp_age_df)){
  a <- fmp_age_df[row, paste0(AGE_MENO, "0.0")]
  b <- fmp_age_df[row, paste0(AGE_MENO, "1.0")]
  c <- fmp_age_df[row, paste0(AGE_MENO, "2.0")]
  vec <- c(a, b, c)                                        # Create vector values for age at FMP
  vec <- vec[!is.na(vec)]                                  # Keep only non-NA values
  if (length(unique(vec))>2){                              # If there is more than one value for age at FMP, then:
    fmp_age_range <- c(fmp_age_range, diff(range(vec)))    # Calculate difference in ages and add to vector
    if (diff(range(vec)) > 2){                             # If reported ages at FMP are more than 2 years apart, then:
      problem_eids <- c(problem_eids, fmp_age_df[row, ID]) # Add individual ID to vector (of IDs to exclude)
    }
  }
}
# Create data frames of individuals listed in the "problem" ID vectors
fmp_age_exclude <- fmp_age_df[(fmp_age_df[,ID] %in% problem_eids),]
# Remove individuals with reported ages at FMP more than 2 years apart
UKBBv4 <- UKBBv3[!(UKBBv3[,ID] %in% fmp_age_exclude[,ID]),]
# Count sample size and execute print statements
n_fmp_age_exclude <- nrow(fmp_age_exclude)
n_UKBBv4 <- nrow(UKBBv4)
n_multiple_FMPage <- sum(rowSums(!is.na(UKBBv3[c(paste0(AGE_MENO, "0.0"), paste0(AGE_MENO, "1.0"), paste0(AGE_MENO, "2.0"))])) >= 2)
noquote(paste0("Number of individuals with multiple ages at menopause which range by more than 2 years: ", n_fmp_age_exclude))
noquote(paste0("Sample size following restriction to consistent age of menopause: ", n_UKBBv4))
noquote(paste0("Number of participants who answered menopause age question more than once: ", n_multiple_FMPage))

## Restrict to individuals with age at menopause >=40
# Age at menopause variables
fmp_age_0 <- paste0(AGE_MENO, "0.0")
fmp_age_1 <- paste0(AGE_MENO, "1.0")
fmp_age_2 <- paste0(AGE_MENO, "2.0")
# Code "do not know" and "prefer not to answer" as NA (these are coded as -1 and -3)
UKBBv4[[fmp_age_0]][UKBBv4[[fmp_age_0]] < 0] <- NA
UKBBv4[[fmp_age_1]][UKBBv4[[fmp_age_1]] < 0] <- NA
UKBBv4[[fmp_age_2]][UKBBv4[[fmp_age_2]] < 0] <- NA
# Create empty column for age at menopause variable
UKBBv4$fmp_age <- NA
# Loop through age at menopause columns to find non NA values to send into the new FMP age column
# This loop priorities the earliest recorded age at menopause (takes first reported age)
for (row in 1:nrow(UKBBv4)){
  if (!is.na(UKBBv4[row, fmp_age_0])){               # If there is a value in the first menopause age column
    UKBBv4[row, "fmp_age"] <- UKBBv4[row, fmp_age_0] # Then send this value to the new menopause age column
  }
  else if (!is.na(UKBBv4[row, fmp_age_1])){          # Else, if there is a value in the second menopause age column
    UKBBv4[row, "fmp_age"] <- UKBBv4[row, fmp_age_1] # Then send this value to the new menopause age column
  }
  else if (!is.na(UKBBv4[row, fmp_age_2])){          # Else, if there is a value in the third menopause age column
    UKBBv4[row, "fmp_age"] <- UKBBv4[row, fmp_age_2] # Then send this value to the new menopause age column
  }
}
# Filter to those with an age of FMP over 40
UKBBv5 <- UKBBv4 %>% filter(!is.na(fmp_age))         # Remove NA values
UKBBv6 <- UKBBv5 %>% filter(fmp_age >= 40)           # Restrict to over 40
# Count sample and execute print statement
n_UKBBv5 <- nrow(UKBBv5)
n_UKBBv6 <- nrow(UKBBv6)
noquote(paste0("Number of individuals with no reported age at menopause: ", n_UKBBv4 - n_UKBBv5))
noquote(paste0("Number of individuals with age at menopause less than 40 years: ", n_UKBBv5 - n_UKBBv6))
noquote(paste0("Sample size following restriction to menopause age over 40 years: ", n_UKBBv6))

## Exclude hysterectomy and/or bilateral oophorectomy
# Hysterectomy and bilateral oophorectomy variables
hyst0 <- paste0(HYSTEREC, "0.0")
hyst1 <- paste0(HYSTEREC, "1.0")
hyst2 <- paste0(HYSTEREC, "2.0")
bila0 <- paste0(BILAT_OP, "0.0")
bila1 <- paste0(BILAT_OP, "1.0")
bila2 <- paste0(BILAT_OP, "2.0")
# Create subset of individuals with reported hysterectomy
hyst <- subset(UKBBv6, get(hyst0) == 1 | get(hyst1) == 1 | get(hyst2) == 1)
# Create subset of individuals with reported bilateral oophorectomy
bila <- subset(UKBBv6, get(bila0) == 1 | get(bila1) == 1 | get(bila2) == 1)
# Create subset of individuals with both hysterectomy and bilateral oophorectomy
hyst_bila <- inner_join(hyst, bila)
# Remove individuals with reported hysterectomy or bilateral oophorectomy
UKBBv7 <- UKBBv6[!(UKBBv6[,ID] %in% hyst[,ID]),] # Remove hysterectomy
UKBBv8 <- UKBBv7[!(UKBBv7[,ID] %in% bila[,ID]),] # Remove bilateral oophorectomy
# Count sample sizes and execute print statements
n_hyst <- nrow(hyst)
n_bila <- nrow(bila)
n_both <- nrow(hyst_bila)
n_UKBBv8 <- nrow(UKBBv8)
noquote(paste0("Number of individuals with reported hysterectomy: ", n_hyst))
noquote(paste0("Number of individuals with reported bilateral oophorectomy: ", n_bila))
noquote(paste0("Number of individuals with reported both hysterectomy and bilateral oophorectomy: ", n_both))
noquote(paste0("Sample size following removal of hystectomy and bilateral oophorectomy: ", n_UKBBv8))

## Exclude those who have hospital inpatient records of uterine ablations (or similar)
opr_codes <- c("Q07", "Q08", "Q10", "Q16") # Operation codes to exclude
operation_colnames <- colnames(select(UKBBv8, starts_with(OPR_CODE))) # Extract operative procedure column names
UKBBv8$uterus_operation <- 0 # Create column for whether participant has had an excluded operation (1) or not (0)
# Loop through each column and code, assigning "1" to the uterus_operation column if the code matches
for (operation_column in operation_colnames){
  for (operation_code in opr_codes){
    UKBBv8$uterus_operation <- ifelse(grepl(operation_code, UKBBv8[[operation_column]]), "1", UKBBv8$uterus_operation)
  }
}
# Count number of participants with each operation code (skippable)
skip <- "yes" # Type "no" to recount number of participants with each operation code
if (skip == "no"){
  for (operation_code in opr_codes){
    counter <- 0
    for (operation_column in operation_colnames){
      for (row in 1:nrow(UKBBv8)){
        if (grepl(operation_code, UKBBv8[row, operation_column])){
          counter <- counter + 1
        }
      }
    }
    assign(paste0(operation_code, "_n"), counter)
  }
}
# Number of individuals with uterine operation
n_opr <- nrow(subset(UKBBv8, UKBBv8$uterus_operation == 1))
# Remove individuals with uterine operations
UKBBv8 <- subset(UKBBv8, UKBBv8$uterus_operation == 0)
# Print statements
n_UKBBv8 <- nrow(UKBBv8)
noquote(paste0("Number of individuals with hospital inpatient record of uterine ablation (or similar): ", n_opr))
noquote(paste0("Sample size following removal of those with uterine ablations: ", n_UKBBv8))

## Exclude those with the mirena coil
# Create vector of medications to exclude
medicines <- c("1140921814", "1140921822") # 'mirena 52mg intrauterine system' and 'mirena 20mcg/24hrs intrauterine system'
# Create vector of medication code columns
med_colnames <- colnames(select(UKBBv8, starts_with(MED_CODE))) # Extract medication/treatment code column names
# Create column for whether or not (0/1) the participant has the mirena coil
UKBBv8$mirena <- 0 # Fill with 0 ("no") initially
# Loop through rows and columns to find the medication codes of interest and change the mirena column to 1 ("yes") for those who have it
for (row in 1:nrow(UKBBv8)){
  for (column in med_colnames){
    for (med in medicines){
      if (!is.na(UKBBv8[row, column])){  # If medication code cell is not empty
        if (UKBBv8[row, column] == med){ # And if the cell matches medication code
          UKBBv8[row, "mirena"]  <- 1    # Then assign "1" to mirena column
        }
      }
    }
  }
}
# Number of individuals with mirena coil
n_mirena <- nrow(subset(UKBBv8, UKBBv8$mirena == 1))
# Remove individuals with mirena coil
UKBBv8 <- subset(UKBBv8, UKBBv8$mirena == 0)
# Print statements
n_UKBBv8 <- nrow(UKBBv8)
noquote(paste0("Number of individuals with mirena coil: ", n_mirena))
noquote(paste0("Sample size following removal of those with mirena coil: ", n_UKBBv8))

## Exclude those who reported starting to take a contraceptive pill at the same age they reported menopause
# Create column for whether to exclude (yes/no: 1/0) based on age started contraceptive pill
UKBBv8$pill_age_equals_FMP_age <- 0 # Fill with 0 ('no') initially
# Create vector of contraceptive pill start age column names
pill_started_colnames <- colnames(select(UKBBv8, starts_with(PILL_START))) # Extract contraceptive pill starting age column names
# Loop through rows and columns to find ages when started contraceptive pill equal to FMP age and assign these 1 ("yes")
for (row in 1:nrow(UKBBv8)){
  for (column in pill_started_colnames){
    if (!is.na(UKBBv8[row, column])){
      if (UKBBv8[row, column] == (UKBBv8[row, "fmp_age"])){
        UKBBv8[row, "pill_age_equals_FMP_age"] <- 1
      }
    }
  }
}
# Number of individuals with age started contraceptive pill equal to FMP age
n_pill <- nrow(subset(UKBBv8, UKBBv8$pill_age_equals_FMP_age == 1))
# Remove individuals with age started contraceptive pill equal to FMP age
UKBBv8 <- subset(UKBBv8, UKBBv8$pill_age_equals_FMP_age==0)
# Print statements
n_UKBBv8 <- nrow(UKBBv8)
noquote(paste0("Number of individuals with age started contraceptive pill equal to FMP age: ", n_pill))
noquote(paste0("Sample size following removal of those with age started contraceptive pill equal to FMP age: ", n_UKBBv8))

# MATCH MALE PARTICIPANTS TO FEMALE PARTICIPANTS
# ******************************************************************************
## Restrict to male participants (coded as 1)
UKBB_male <- subset(UKBB_all, get(SEX) == 1)
# Count sample size and execute print statements
n_males <- nrow(UKBB_male)
noquote(paste0("Number of individuals removed based on sex: ", n_UKBB - n_males))
noquote(paste0("Sample size following restriction to males: ", n_males))

## Extract age at most recent SR (self-report) assessment
# (This ensures that male participants are matched to a female participant with data available until the same age)
# Create names for age at SR columns
sr_age_0 <- paste0(SR_AGE, "0.0")
sr_age_1 <- paste0(SR_AGE, "1.0")
sr_age_2 <- paste0(SR_AGE, "2.0")
# Create counter for missing values (check)
n_missing_sr <- 0
# Loop through SR age entries starting from most recent, add to column if value exists
for (df_name in c("UKBBv8", "UKBB_male")) {
  df <- get(df_name)
  for (row in 1:nrow(df)){
    df[["sr_age"]] <- NA                     # Create empty column for age at most recent self-report (SR) assessment
    if (!is.na(df[row, sr_age_2])){          # If age at most recent SR assessment exists
      df[row, "sr_age"] <- df[row, sr_age_2] # Add this value to SR age column
    }
    else if (!is.na(df[row, sr_age_1])){     # Else, if age at second most recent SR assessment exists
      df[row, "sr_age"] <- df[row, sr_age_1] # Add this value to SR age column
    }
    else if (!is.na(df[row, sr_age_0])){     # Else, if age at initial SR assessment exists
      df[row, "sr_age"] <- df[row, sr_age_0] # Add this value to SR age column
    }
    else {
      n_missing_sr <- n_missing_sr + 1       # Else add one to missing SR age counter
    }
  }
  assign(df_name, df)
}

# Set age of FMP (proxy) in male participants
set.seed(1)
## Match based on sr age
# Create vector of unique SR ages
sr_age_vec <- sort(unique(UKBBv8$sr_age))
# Create empty vector for indices of rows to remove
indices_list <- c()
# Match male sample to female sample by sr age
for (age in sr_age_vec){
  n_female <- nrow(subset(UKBBv8, UKBBv8$sr_age == age))
  indices <- which(UKBB_male$sr_age == age)
  indices <- sample(indices, n_female)
  indices_list <- c(indices_list, indices)
}
UKBB_male <- UKBB_male[indices_list, ]

# Match FMP ages to SR ages the same as in the female sample
UKBB_male <- UKBB_male[order(UKBB_male$sr_age),] # Sort males by sr age
UKBBv9_sorted <- UKBBv8[order(UKBBv8$sr_age),]   # Sort females by sr age
UKBB_male$fmp_age <- UKBBv9_sorted$fmp_age       # Assign FMP ages to males


4. Diagnosis and onset age extraction

Extracts psychiatric diagnoses and corresponding onset ages.

# 4. DIAGNOSIS AND ONSET AGE EXTRACTION -------------------------------------------------------------------------
# This section is divided by source of diagnosis/onset age data
for (df_name in c("UKBBv8", "UKBB_male")) {
  df <- get(df_name)
  
  # SELF-REPORTED DIAGNOSES FROM ASSESSMENT CENTRE
  # ******************************************************************************
  ## Generate diagnosis and onset age columns
  # Create lists for diagnosis status, onset age and onset relative to FMP column names
  illnesses_dgn_colnames  <- all_illnesses # Create list for diagnosis columns
  illnesses_age_colnames  <- all_illnesses # Create list for diagnosis age columns
  illnesses_fmp_colnames  <- all_illnesses # Create list for diagnosis age relative to FMP columns
  illnesses_sta_colnames  <- all_illnesses # Create list for status columns (diagnosis + onset)
  # Add suffixes to column names
  names(illnesses_dgn_colnames)  <- paste0(names(illnesses_dgn_colnames),"_diagnosed") # Diagnosis columns
  names(illnesses_age_colnames)  <- paste0(names(illnesses_age_colnames),"_age")       # Onset age columns
  names(illnesses_fmp_colnames)  <- paste0(names(illnesses_fmp_colnames),"_delta")     # Onset age relative to FMP columns
  names(illnesses_sta_colnames)  <- paste0(names(illnesses_sta_colnames),"_status")    # Diagnosis status columns (diagnosis + onset)
  # Add columns to dataframe and fill with 0 (for diagnosis status) and NA (for age)
  df[, names(illnesses_dgn_colnames)]  <- lapply(illnesses_dgn_colnames, function(x) rep(0, nrow(df)))  # Diagnosis
  df[, names(illnesses_age_colnames)]  <- lapply(illnesses_age_colnames, function(x) rep(NA, nrow(df))) # Onset age
  df[, names(illnesses_fmp_colnames)]  <- lapply(illnesses_fmp_colnames, function(x) rep(NA, nrow(df))) # Onset relative to FMP
  df[, names(illnesses_sta_colnames)]  <- lapply(illnesses_sta_colnames, function(x) rep(0, nrow(df)))  # Diagnosis status columns (diagnosis + onset)
  
  ## Extract diagnoses and onset ages
  # Create vector of onset age column suffixes
  onset_colnames <- colnames(select(df, starts_with(SR_I))) # Extract SR (self-report) onset column names
  sr_suffixes <- gsub(SR_I, "", onset_colnames)             # Remove prefix to leave vector containing only suffixes
  # Make onset ages numeric
  for (suffix in sr_suffixes){
    onset_col <- paste0(SR_I_AGE, suffix)
    df[, onset_col] <- as.numeric(df[, onset_col])
  }
  # Loop through rows and columns to extract onset ages from self-report data
  for (row in 1:nrow(df)){
    for (suffix in sr_suffixes){
      for (illness in names(sr_illnesses)){
        ill_code     <- sr_illnesses[[illness]]       ## SET VARIABLE: Coding for illness of interest
        ill_dgn_col  <- paste0(illness, "_diagnosed") ## SET VARIABLE: Name of illness diagnosis column
        ill_age_col  <- paste0(illness, "_age")       ## SET VARIABLE: Name of illness age column
        ill_fmp_col  <- paste0(illness, "_delta")     ## SET VARIABLE: Name of onset relative to FMP column
        disorder_col <- paste0(SR_I, suffix)          ## SET VARIABLE: Column name for disorders
        disorder     <- df[row, disorder_col]         ## SET VARIABLE: Disorder (code)
        onset_col    <- paste0(SR_I_AGE, suffix)      ## SET VARIABLE: Column name for onset age
        onset        <- df[row, onset_col]            ## SET VARIABLE: Onset age
        fmp          <- df[row, "fmp_age"]            ## SET VARIABLE: Age at FMP
        if (!is.na(disorder) && !is.na(onset)){       # If disorder and corresponding onset are not NA
          if (disorder == ill_code){                  # And if the disorder matches illness code
            df[row, ill_dgn_col]  <- 1                # Then assign "1" to illness diagnosis column
            df[row, ill_age_col]  <- onset            # And assign onset to illness age column
            df[row, ill_fmp_col]  <- onset-fmp        # And assign onset relative to FMP
          }
        }
      }
    }
  }
  
  # DIAGNOSES FROM MENTAL HEALTH QUESTIONNAIRE
  # ******************************************************************************
  ## Extract diagnoses and onset ages
  # Create vector of onset age column suffixes
  mhq_colnames <- colnames(select(df, starts_with(MHQ_STAT))) # Extract MHQ diagnosis column names
  mhq_suffixes <- gsub(MHQ_STAT, "", mhq_colnames)            # Remove prefix to leave vector containing only suffixes
  # BUG FIX: Make onset ages numeric
  df[, MHQ_P_AGE] <- as.numeric(df[, MHQ_P_AGE])
  # Loop through rows and columns to extract onset ages from MHQ data
  for (illness in names(mhq_illnesses)){
    ill_code     <- mhq_illnesses[[illness]]      ## SET VARIABLE: Coding for illness of interest
    ill_dgn_col  <- paste0(illness, "_diagnosed") ## SET VARIABLE: Name of illness diagnosis column
    ill_age_col  <- paste0(illness, "_age")       ## SET VARIABLE: Name of illness age column
    ill_fmp_col  <- paste0(illness, "_delta")     ## SET VARIABLE: Name of onset relative to FMP column
    for (suffix in mhq_suffixes){
      disorder_col <- paste0(MHQ_STAT, suffix)    ## SET VARIABLE: Column name for disorders
      for (row in 1:nrow(df)){
        disorder     <- df[row, disorder_col]     ## SET VARIABLE: Disorder (code)
        onset        <- df[row, MHQ_P_AGE]        ## SET VARIABLE: Onset age
        fmp          <- df[row, "fmp_age"]        ## SET VARIABLE: Age at FMP
        if (!is.na(disorder) && !is.na(onset)){   # If disorder and corresponding onset are not NA
          if (disorder == ill_code){              # And if the disorder matches illness code
            df[row, ill_dgn_col]  <- 1            # Then assign "1" to illness diagnosis column
            df[row, ill_age_col]  <- onset        # And assign onset to illness age column
            df[row, ill_fmp_col]  <- onset-fmp    # And assign onset relative to FMP
          }
        }
      }
    }
  }
  
  ## Major depressive disorder
  # Create column for strict depression status
  df$dp_strict_diagnosed <- 0
  df$dp_strict_status    <- 0
  df$dp_strict_age       <- NA
  df$dp_strict_delta     <- NA
  # Create vector of depression MHQ questions
  MHQ_MDD_cardinal_symptoms <- c(MHQ_MD_C1, MHQ_MD_C2)
  MHQ_MDD_other_symptoms    <- c(MHQ_MD_S1, MHQ_MD_S2, MHQ_MD_S3, MHQ_MD_S4, MHQ_MD_S5, MHQ_MD_S6)
  # Substance abuse
  substance_alcohol <- 1408
  substance_opioid  <- 1409
  substance_other   <- 1410
  substances <- list(substance_alcohol = substance_alcohol, substance_opioid = substance_opioid, substance_other = substance_other)
  df$substance_abuse <- 0
  for (row in 1:nrow(df)){
    for (suffix in sr_suffixes){
      for (substance in names(substances)){
        ill_code     <- substances[[substance]]       ## SET VARIABLE: Coding for illness of interest
        disorder_col <- paste0(SR_I, suffix)          ## SET VARIABLE: Column name for disorders
        disorder     <- df[row, disorder_col]         ## SET VARIABLE: Disorder (code)
        if (!is.na(disorder) & disorder == ill_code){ # If disorder matches illness code
          df[row, "substance_abuse"]  <- 1            # Then assign "1" to illness diagnosis column
        }
      }
    }
  }
  # Loop for diagnosis
  n_no_bipolar <-0
  n_no_mania_psychosis <- 0
  n_no_substance <- 0
  n_enoughsymptoms <- 0
  n_impact <- 0
  for (row in 1:nrow(df)){
    cardinal_symptoms  <- 0
    total_symptoms     <- 0
    no_bipolar         <- is.na(df[row, BIPOLAR]) | ((df[row, BIPOLAR]!=1 && df[row, BIPOLAR]!=2))
    no_mania_psychosis <- df[row, "bp_diagnosed"]!=1 && df[row, "sz_diagnosed"]!=1
    no_substance       <- df[row, "substance_abuse"]!=1
    impact             <- !is.na(df[row, MHQ_MD_I]) && df[row, MHQ_MD_I] == 3 # "A lot"
    # Cardinal symptoms
    for (s in MHQ_MDD_cardinal_symptoms){
      if (!is.na(df[row, s]) & df[row, s] == 1){
        cardinal_symptoms <- cardinal_symptoms + 1
        total_symptoms    <- total_symptoms + 1
      }
    }
    # Other symptoms (only if cardinal symptoms are present)
    if (cardinal_symptoms > 0){
      for (s in MHQ_MDD_other_symptoms){
        if (df[row, s] > 0){
          total_symptoms    <- total_symptoms + 1
        }
      }
    }
    # Change strict depression status if 5 or more symptoms are reported
    if (total_symptoms >= 5 && no_bipolar && no_mania_psychosis && no_substance && impact){
      df[row, "dp_strict_diagnosed"] <- 1
    }
  }
  # Loop for onset age and status
  for (row in 1:nrow(df)){
    if (df[row, "dp_strict_diagnosed"] == 1){
      if (df[row, MHQ_D_AGE] >= 0){
        df[row, "dp_strict_status"] <- 1
        df[row, "dp_strict_age"]    <- df[row, MHQ_D_AGE]
        df[row, "dp_strict_delta"]  <- df[row, MHQ_D_AGE] - df[row, "fmp_age"]
      }
    }
  }
  ## Print statements
  noquote(paste0("Individuals who answered depression MHQ questions: ", sum(!is.na(df[[MHQ_MD_C1]]))))
  noquote(paste0("Individuals who did not answer depression MHQ questions: ", sum(is.na(df[[MHQ_MD_C1]]))))
  noquote(paste0("Individuals with strict depression: ", sum(df$dp_strict_diagnosed==1)))
  noquote(paste0("Individuals with strict depression (and SR onset age): ", nrow(subset(df, dp_age > 0 & dp_strict_diagnosed == 1))))
  noquote(paste0("Individuals with strict depression (and MHQ onset age): ", sum(df$dp_strict_status==1)))
  
  # DIAGNOSES FROM MULTIPLE SOURCES
  # ******************************************************************************
  #### PSYCHOSIS COMBINED
  df$psychosis_diagnosed[df$sz_diagnosed == 1]     <- 1
  df$psychosis_diagnosed[df$mhq_sz_diagnosed == 1] <- 1
  df$psychosis_diagnosed[df$mhq_ps_diagnosed == 1] <- 1
  for (row in 1:nrow(df)){
    if (df[row, "psychosis_diagnosed"] == 1){
      if (!is.na(df[row, "sz_age"])){
        df[row, "psychosis_age"]   <- df[row, "sz_age"]
        df[row, "psychosis_delta"] <- df[row, "sz_delta"]
      }
      else if (!is.na(df[row, "mhq_sz_age"])){
        df[row, "psychosis_age"]   <- df[row, "mhq_sz_age"]
        df[row, "psychosis_delta"] <- df[row, "mhq_sz_delta"]
      }
      else if (!is.na(df[row, "mhq_ps_delta"])){
        df[row, "psychosis_age"]   <- df[row, "mhq_ps_age"]
        df[row, "psychosis_delta"] <- df[row, "mhq_ps_delta"]
      }
      else {
        df[row, "psychosis_age"]   <- -1
      }
    }
  }
  
  #### Substance abuse
  df$substanceabuse_diagnosed[df$sub_alc_diagnosed == 1] <- 1
  df$substanceabuse_diagnosed[df$sub_opi_diagnosed == 1] <- 1
  df$substanceabuse_diagnosed[df$sub_oth_diagnosed == 1] <- 1
  for (row in 1:nrow(df)){
    if (df[row, "substanceabuse_diagnosed"] == 1){
      if (!is.na(df[row, "sub_alc_age"])){
        df[row, "substanceabuse_age"]   <- df[row, "sub_alc_age"]
        df[row, "substanceabuse_delta"] <- df[row, "sub_alc_delta"]
      }
      else if (!is.na(df[row, "sub_opi_age"])){
        df[row, "substanceabuse_age"]   <- df[row, "sub_opi_age"]
        df[row, "substanceabuse_delta"] <- df[row, "sub_opi_delta"]
      }
      else if (!is.na(df[row, "sub_oth_age"])){
        df[row, "substanceabuse_age"]   <- df[row, "sub_oth_age"]
        df[row, "substanceabuse_delta"] <- df[row, "sub_oth_delta"]
      }
      else {
        df[row, "substanceabuse_age"]   <- -1
      }
    }
  }
  
  ### STATUS
  ## Set status as 0 for those who are diagnosed but have error/missing codes as onset ages
  # Loop through all illnesses and revert diagnosis status to 0 if onset is not >0 (as negative numbers are missing codes)
  for (row in 1:nrow(df)){
    for (illness in names(all_illnesses)){
      ill_dgn  <- paste0(illness, "_diagnosed")## SET VARIABLE: Name of illness diagnosis column
      ill_age  <- paste0(illness, "_age")      ## SET VARIABLE: Name of illness age column
      ill_fmp  <- paste0(illness, "_delta")    ## SET VARIABLE: Name of onset relative to FMP column
      ill_sta  <- paste0(illness, "_status")   ## SET VARIABLE: Name of illness status column
      df[row, ill_sta] <- df[row, ill_dgn]
      if (!is.na(df[row, ill_age]) && (df[row, ill_age]) < 0){
        df[row, ill_sta] <- 0
        df[row, ill_age] <- NA
        df[row, ill_fmp] <- NA
      }
    }
  }
  
  ## Count sample sizes and execute print statements
  for (illness in names(all_illnesses)){
    diagnosed    <- paste0(illness, "_diagnosed")   ## SET VARIABLE: name of diagnosed column
    status       <- paste0(illness, "_status")      ## SET VARIABLE: name of illness status column
    age          <- paste0(illness, "_age")         ## SET VARIABLE: name of onset age column
    delta        <- paste0(illness, "_delta")       ## SET VARIABLE: name of onset age relative to FMP column
    n_diagnosed  <- paste0("n_", illness, "_dgn")   ## SET VARIABLE: name of illness status counter
    n_status     <- paste0("n_", illness, "_age")   ## SET VARIABLE: name of illness with onset age counter
    assign(n_diagnosed, sum(df[[diagnosed]]==1))    # Count those with illness diagnosis
    assign(n_status, sum(df[[status]]==1))          # Count those with illness and onset age
    print(paste0("Individuals with self-reported ", illness, " diagnosis: ", get(n_diagnosed)), quote = FALSE)
    print(paste0("Individuals with self-reported ", illness, " diagnosis but no age at onset: ", (get(n_diagnosed)) - get(n_status)), quote = FALSE)
    print(paste0("Individuals with self-reported ", illness, " diagnosis and age at onset: ", get(n_status)), quote = FALSE)
  }
  
  ## Other diagnoses
  otherillness_diagnosed <- colnames(select(df, ends_with("diagnosed") 
                                            & contains(c("ptsd", "ed_", "stress", "ocd", "insom", "substanceabuse", "an"))
                                            & !contains(c("combined"))))
  otherillness_prefixes <- str_replace(otherillness_diagnosed, "_diagnosed", "")
  df$otherillness_diagnosed <- 0
  df$otherillness_status    <- 0
  df$otherillness_age       <- NA
  df$otherillness_delta     <- NA
  for (row in 1:nrow(df)){
    # Find diagnoses with onset ages
    for (i in otherillness_prefixes){
      diagnosed <- paste0(i, "_diagnosed")
      status    <- paste0(i, "_status")
      age       <- paste0(i, "_age") 
      delta     <- paste0(i, "_delta")   
      if (df[row, diagnosed] == 1 && df[row, status] == 1){
        df[row, "otherillness_diagnosed"] <- 1
        df[row, "otherillness_status"]    <- 1
        if (is.na(df[row, "otherillness_delta"]) || (df[row, delta] < df[row, "otherillness_delta"])){
          df[row, "otherillness_delta"]   <- df[row, delta]
          df[row, "otherillness_age"]     <- df[row, age]
        }
      }
      if ((df[row, diagnosed] == 1 && df[row, status] == 0)
          && (df[row, "otherillness_status"] == 0)){
        df[row, "otherillness_diagnosed"] <- 1
        df[row, "otherillness_status"]    <- 0
        df[row, "otherillness_delta"]     <- NA
        df[row, "otherillness_age"]       <- NA
      }
    }
  }
  ## Print statements
  noquote(paste0("Individuals with other illness: ", sum(df$otherillness_diagnosed==1)))
  noquote(paste0("Individuals with other illness and any missing onset age: ", nrow(subset(df, otherillness_diagnosed==1 & otherillness_status==0))))
  noquote(paste0("Individuals with other illness and corresponding onset age: ", sum(df$otherillness_status==1)))
  
  ## All disorders
  illness_prefixes <- c("dp_strict", "bp", "psychosis", "otherillness")
  
  df$combined_diagnosed <- 0
  df$combined_status    <- 0
  df$combined_age       <- NA
  df$combined_delta     <- NA
  
  for (row in 1:nrow(df)){
    # Find diagnoses with onset ages
    for (i in illness_prefixes){
      diagnosed <- paste0(i, "_diagnosed")
      status    <- paste0(i, "_status")
      age       <- paste0(i, "_age") 
      delta     <- paste0(i, "_delta")   
      if (df[row, diagnosed] == 1 && df[row, status] == 1){
        df[row, "combined_diagnosed"] <- 1
        df[row, "combined_status"]    <- 1
        if (is.na(df[row, "combined_delta"]) || (df[row, delta] < df[row, "combined_delta"])){
          df[row, "combined_delta"]   <- df[row, delta]
          df[row, "combined_age"]     <- df[row, age]
        }
      }
    }
    # Find diagnoses with NO onset age and override
    for (i in illness_prefixes){
      diagnosed <- paste0(i, "_diagnosed")
      status    <- paste0(i, "_status")
      age       <- paste0(i, "_age") 
      delta     <- paste0(i, "_delta")   
      if (df[row, diagnosed] == 1 && df[row, status] == 0){
        df[row, "combined_diagnosed"] <- 1
        df[row, "combined_status"]    <- 0
        df[row, "combined_delta"]     <- NA
        df[row, "combined_age"]       <- NA
      }
    }
  }
  
  ## Print statements
  noquote(paste0("Individuals with a psychiatric illness: ", sum(df$combined_diagnosed==1)))
  noquote(paste0("Individuals with a psychiatric illness and any missing onset age: ", nrow(subset(df, combined_diagnosed==1 & combined_status==0))))
  noquote(paste0("Individuals with a psychiatric illness and corresponding onset age: ", sum(df$combined_status==1)))
  
  assign(df_name, df)
}
# Save dataframe for use in analysis script
save(UKBBv8, file = paste0(DATA_DIR, "/clean_UKBB_dataframe_f"))
save(UKBB_male, file = paste0(DATA_DIR, "/clean_UKBB_dataframe_m"))

Settings

Settings

Initial set up. Includes the following:

  • Loading of packages
  • Specifying paths to data directories
  • Loading data
  • Storing UK Biobank codes as variables (for readability)
# Load packages
library(tidyverse)      # Packages for data wrangling
library(survival)       # Survival analysis
library(rateratio.test) # Rate ratio test

## DIRECTORIES
DATA_DIR  <- "~/Perimenopause/Data"         # Data directory
PLOT_DIR  <- "~/Perimenopause/Plots"        # Output directories for plots to be saved

## Load data
load(paste0(DATA_DIR, "/clean_UKBB_dataframe_f"))
load(paste0(DATA_DIR, "/clean_UKBB_dataframe_m"))

## CODES (data field IDs and illness codes)
# Variables with only one value
ID        <- "f.eid"                        # Individual ID
SEX       <- "f.31.0.0"                     # Sex
YOB       <- "f.34.0.0"                     # Year of birth
MHQ_D_AGE <- "f.20433.0.0"                  # Age at first episode of depression (MHQ)
MHQ_P_AGE <- "f.20461.0.0"                  # Age when first had unusual or psychotic experience (MHQ)
MHQ_DATE  <- "f.20400.0.0"                  # Date of completing mental health questionnaire
MHQ_MD_C1 <- "f.20446.0.0"                  # Mental health questionnaire, major depression cardinal symptom 1
MHQ_MD_C2 <- "f.20441.0.0"                  # Mental health questionnaire, major depression cardinal symptom 2
MHQ_MD_S1 <- "f.20536.0.0"                  # Mental health questionnaire, major depression symptom 1
MHQ_MD_S2 <- "f.20532.0.0"                  # Mental health questionnaire, major depression symptom 2
MHQ_MD_S3 <- "f.20449.0.0"                  # Mental health questionnaire, major depression symptom 3
MHQ_MD_S4 <- "f.20450.0.0"                  # Mental health questionnaire, major depression symptom 4
MHQ_MD_S5 <- "f.20435.0.0"                  # Mental health questionnaire, major depression symptom 5
MHQ_MD_S6 <- "f.20437.0.0"                  # Mental health questionnaire, major depression symptom 6
MHQ_MD_I  <- "f.20440.0.0"                  # Mental health questionnaire, major depression impact
MHQ_MD_L  <- "f.20442.0.0"                  # Mental health questionnaire, major depression lifetime
BIPOLAR   <- "f.20126.0.0"                  # Bipolar and major depression status
TOWNSEND  <- "f.189.0.0"                    # Townsend deprivation index at recruitment
# Variables with multiple values (from one measure)
MHQ_STAT  <- "f.20544."                     # Mental health problems ever diagnosed by a professional (MHQ)
OPR_CODE  <- "f.41272."                     # Operative procedures - OPCS4
# Variables with multiple values (from repeat measures)
ASCE_DATE <- "f.53."                        # Date of attending assessment center
ASCE_AGE  <- "f.21003."                     # Age when attended assessment center
ETHNICITY <- "f.21000."                     # Ethnic background
BMI       <- "f.21001."                     # Body mass index (BMI)
SMOKE_STAT<- "f.20116."                     # Smoking status
ALC_FREQ  <- "f.1558."                      # Alcohol intake frequency
HAD_MENO  <- "f.2724."                      # Had menopause
AGE_MENO  <- "f.3581."                      # Age at menopause (last menstrual period)
HYSTEREC  <- "f.3591."                      # Ever had hysterectomy (womb removed)
BILAT_OP  <- "f.2834."                      # Bilateral oophorectomy (both ovaries removed)
PILL_START<- "f.2794."                      # Age started oral contraceptive pill
SR_I      <- "f.20002."                     # Non-cancer illness code, self-reported
MED_CODE  <- "f.20003."                     # Treatment/medication code
SR_I_AGE  <- "f.20009."                     # Interpolated age of participant when illness first diagnosed
SR_AGE    <- "f.21003."                     # Age when attended assessment center
DEP_GP    <- "f.2090."                      # Seen doctor (GP) for nerves, anxiety, tension or depression
DEP_PSY   <- "f.2100."                      # Seen a psychiatrist for nerves, anxiety, tension or depression
# Illness codes for self-report/assessment center (field ID 20002)
dp        <- 1286                           # Depression
sz        <- 1289                           # Schizophrenia
bp        <- 1291                           # Mania/bipolar disorder/manic depression
an        <- 1287                           # Anxiety/panic attacks
nb        <- 1288                           # Nervous breakdown
ptsd      <- 1469                           # Post-traumatic stress disorder    
ed        <- 1470                           # Anorexia/bulimia/other eating disorder
stress    <- 1614                           # Stress
ocd       <- 1615                           # Obsessive compulsive disorder (OCD)
insom     <- 1616                           # Insomnia 
sub_alc   <- 1408                           # Alcohol dependency
sub_opi   <- 1409                           # Opioid dependency
sub_oth   <- 1410                           # Other substance abuse/dependency
# List of self-report illness codes
sr_illnesses <- list(dp = dp, sz = sz, bp = bp, an = an, nb = nb,
                     ptsd = ptsd, ed = ed, stress = stress, ocd = ocd, insom = insom,
                     sub_alc = sub_alc, sub_opi = sub_opi, sub_oth = sub_oth) 
# Illness codes for MHQ diagnoses (field ID 20544)
mhq_sz    <- 2                              # Schizophrenia
mhq_ps    <- 3                              # Any other type of psychosis or psychotic illness
# List of MHQ illness codes
mhq_illnesses <- list(mhq_sz = mhq_sz, mhq_ps = mhq_ps) 
# List of all illness codes
all_illnesses <- c(sr_illnesses, mhq_illnesses, psychosis = NA, substanceabuse = NA)

Kaplan-Meier analysis

Kaplan-Meier analysis

This section is the main analysis and is organised into the following code chunks:

  1. Length of follow up
  2. Time to event
  3. Kaplan-Meier model


1. Length of follow up

This section determines the age at most recent follow up for each participant, relative to age at menopause.

for (df_name in c("UKBBv8", "UKBB_male")) {
  df <- get(df_name)
  ## Extract age at most recent date of MHQ
  # Keep only first 4 characters of MHQ date (leaves just the year)
  df$mhq_date <- substr(df[, MHQ_DATE], start = 1, stop = 4)
  # Make column values numeric (not string)
  df$mhq_date <- as.numeric(df$mhq_date)
  # Create empty column for age at MHQ
  df$mhq_age <- NA
  # Create counter for missing values (code check: should be 0)
  count_missing_mhq <- 0
  # Loop through rows, calculate age at MHQ from year and birth year if available
  for (row in 1:nrow(df)){
    mhq_year <- df[row, "mhq_date"]
    bir_year <- df[row, YOB]
    if (!is.na(mhq_year) && !is.na(bir_year)){  # If year at MHQ and birth year both exist
      df[row, "mhq_age"] <- mhq_year - bir_year # Then enter age at MHQ as: MHQ year - birth year
    }
    else {
      count_missing_mhq = count_missing_mhq + 1 # Else add one to missing MHQ age counter
    }
  }
  
  ## Create variable for age at most recent follow-up
  # Create empty column for age at most recent follow-up variable
  df$follow_up_age <- NA
  # Create counter for missing values (code check: should be 0)
  count_missing_followupage <- 0
  # Loop for creating age at most recent follow-up variable
  for (row in 1:nrow(df)){
    mhq_age <- df[row, "mhq_age"]
    sr_age  <- df[row, "sr_age"]
    if (!is.na(mhq_age) && !is.na(sr_age)){   # If age at SR and MHQ both exist
      if (mhq_age > sr_age){
        df[row, "follow_up_age"] <- mhq_age   # Use MHQ age if this is larger
      } 
      else {
        df[row, "follow_up_age"] <- sr_age    # Use SR age if this is larger
      }
    }
    else if (!is.na(mhq_age) && is.na(sr_age)){
      df[row, "follow_up_age"] <- mhq_age     # Use MHQ age if it exists and SR age does not
    }
    else if (is.na(mhq_age) && !is.na(sr_age)){
      df[row, "follow_up_age"] <- sr_age      # Use SR age if it exists and MHQ age does not
    }
    else {
      count_missing_followupage <- count_missing_followupage + 1
    }
  }
  
  ## Create variable for years followed-up after FMP
  # Create empty column
  df$follow_up_post_FMP <- NA
  # Loop through rows to create years followed-up after FMP variable
  # If follow-up years is negative (i.e. if menopause age is greater than age at assessment, set variable to 0)
  # This is because some individuals do not have an assessment age entered at later visits at which they reported FMP age
  for (row in 1:nrow(df)){
    df[row, "follow_up_post_FMP"] <- df[row, "follow_up_age"] - df[row, "fmp_age"]
    if (df[row, "follow_up_post_FMP"] < 0){
      df[row, "follow_up_post_FMP"] <- 0
    }
  }
  # SR only
  for (row in 1:nrow(df)){
    df[row, "sr_follow_up_post_FMP"] <- df[row, "sr_age"] - df[row, "fmp_age"]
    if (df[row, "sr_follow_up_post_FMP"] < 0){
      df[row, "sr_follow_up_post_FMP"] <- 0
    }
  }
  # MHQ only
  df$mhq_follow_up_post_FMP <- NA
  for (row in 1:nrow(df)){
    if (!is.na(df[row, MHQ_MD_C1])){
      df[row, "mhq_follow_up_post_FMP"] <- df[row, "mhq_age"] - df[row, "fmp_age"]
      if (df[row, "mhq_follow_up_post_FMP"] < 0){
        df[row, "mhq_follow_up_post_FMP"] <- 0
      }
    }
  }
  assign(df_name, df)
}


2. Time to event

Determines the length of time between an onset of each disorder and age at menopause.

sr_illnesses_list  <- c(dp = NA, bp = NA, otherillness = NA)
srmhq_illnesses    <- c(psychosis = NA, combined = NA)

for (df_name in c("UKBBv8", "UKBB_male")) {
  df <- get(df_name)
  ### Create variable for years until event relative to age at FMP 
  ## MHQ only (MDD)
  df[["time_to_dp_strict"]] <- NA
  for (row in 1:nrow(df)){
    if (df[row, "dp_strict_status"]==1){
      df[row, "time_to_dp_strict"] <- df[row, "dp_strict_delta"]
      }
    else if (df[row, "dp_strict_status"] == 0){
      df[row, "time_to_dp_strict"] <- df[row, "mhq_follow_up_post_FMP"]
      }
  }
  ## SR only
  for (illness in names(sr_illnesses_list)){
    time_to_event <- paste0("time_to_", illness)  ## SET VARIABLE: Time-to-event column name (new)
    df[[time_to_event]] <- NA                      # Create column and fill with NA
    ## Loop through rows to pull out time to event
    illness_status <- paste0(illness, "_status")  ## SET VARIABLE: Illness status column name
    illness_delta <- paste0(illness, "_delta")    ## SET VARIABLE: Illness delta (age relative to FMP) column name
    for (row in 1:nrow(df)){
      if (df[row, illness_status] == 1){
        df[row, time_to_event] <- df[row, illness_delta]
        }
      else if (df[row, illness_status] == 0){
        df[row, time_to_event] <- df[row, "sr_follow_up_post_FMP"]
      }
    }
  }
  ## Both MHQ and SR (psychosis and combined)
  for (illness in names(srmhq_illnesses)){
    time_to_event <- paste0("time_to_", illness)  ## SET VARIABLE: Time-to-event column name (new)
    df[[time_to_event]] <- NA                      # Create column and fill with NA
    ## Loop through rows to pull out time to event
    illness_status <- paste0(illness, "_status")  ## SET VARIABLE: Illness status column name
    illness_delta <- paste0(illness, "_delta")    ## SET VARIABLE: Illness delta (age relative to FMP) column name
    for (row in 1:nrow(df)){
      if (df[row, illness_status] == 1){
        df[row, time_to_event] <- df[row, illness_delta]
        }
      else if (df[row, illness_status] == 0){
        df[row, time_to_event] <- df[row, "follow_up_post_FMP"]
      }
    }
  }
  assign(df_name, df)
}


3. Kaplan-Meier model

Kaplan-Meier analysis model.

all_illnesses_list <- list("dp_strict" = "Major depressive disorder", "bp" = "Mania", 
                           "psychosis" = "Schizophrenia spectrum disorder", "otherillness" = "Other disorders",
                           "dp" = "Depressive symptoms", "combined" = "Combined psychiatric disorders")

for (df_name in c("UKBBv8", "UKBB_male")) {
  df <- get(df_name)
  ifelse(df_name == "UKBB_male", suffix <- "_male", suffix <- "")
  ifelse(df_name == "UKBB_male", participant_sex <- "male", participant_sex <- "female")
  
  stage_ref_time <- -8 

  # Create dataframe for each illness containing only relevant columns (e.g. status and delta)
  for (illness in names(all_illnesses_list)){
    df_name_output    <- paste0(illness, "_kaplanmeier_stage_df", suffix) # Output df name
    illness_diagnosed <- paste0(illness, "_diagnosed")
    illness_status    <- paste0(illness, "_status")
    illness_delta     <- paste0(illness, "_delta")
    time_to_event     <- paste0("time_to_", illness)
    
    if (illness == "dp_strict"){
      df_temp <- select(df, contains(c(illness, MHQ_MD_C1)))
      df_temp <- subset(df_temp, !(get(illness_status)==0 & get(illness_diagnosed)==1))
      df_temp <- subset(df_temp, !is.na(df_temp[[MHQ_MD_C1]]))
    } 
    else {
      df_temp <- select(df, contains(illness))
      df_temp <- subset(df_temp, !(get(illness_status)==0 & get(illness_diagnosed)==1))
    }
    
    df_temp$stage <- NA
    
    for (row in 1:nrow(df_temp)){
      if (df_temp[row, time_to_event] < -10){
        df_temp[row, "stage"] <- -11
        }
      else if (df_temp[row, time_to_event] >= -10 && df_temp[row, time_to_event] <= -6){
        df_temp[row, "stage"] <- -8 # reproductive
      }
      else if (df_temp[row, time_to_event] > -6 && df_temp[row, time_to_event] < -2){
        df_temp[row, "stage"] <- -4
      }
      else if (df_temp[row, time_to_event] >= -2 && df_temp[row, time_to_event] <= 2){
        df_temp[row, "stage"] <- 0 # perimenopause
      }
      else if (df_temp[row, time_to_event] > 2 && df_temp[row, time_to_event] < 6){
        df_temp[row, "stage"] <- 4
      }
      else if (df_temp[row, time_to_event] >= 6 && df_temp[row, time_to_event] <= 10){
        df_temp[row, "stage"] <- 8 # postmenopause
      }
      else if (df_temp[row, time_to_event] > 10){
        df_temp[row, "stage"] <- 11
      }
      else {
        print("Error: time to event variable not classified as a stage")
      }
    }
    
    ## SET VARIABLES ##
    kaplanmeier_model   <- paste0(illness, "_stage_kaplanmeier_model", suffix)   ## SET VARIABLE: Model output
    kaplanmeier_summary <- paste0(illness, "_stage_kaplanmeier_summary", suffix) ## SET VARIABLE: Model summary output
    ## ANALYSIS ##
    model <- survfit(Surv(stage, get(illness_status)) ~ 1, data = df_temp)       # Create Kaplan-Meier model
    summary <- summary(model)
    df_temp <- as.data.frame(summary[c("time", "n.risk", "n.event")])            # Create dataframe, selecting relevant columns
    df_temp$MANUAL_rate_ppy <- df_temp$n.event / (df_temp$n.risk * 4)            # Add column for rate per person-year
    # Add column for rate ratio relative to -10y before FMP:
    df_temp$MANUAL_rr <- df_temp$MANUAL_rate_ppy / df_temp$MANUAL_rate_ppy[df_temp$time==stage_ref_time] 
    ## ASSIGNMENTS ##
    assign(kaplanmeier_model, model)
    assign(kaplanmeier_summary, summary)
    assign(df_name_output, df_temp)
  }
  
  ## Rate ratio loop
  for (illness in names(all_illnesses_list)){
    df_name_output <- paste0(illness, "_kaplanmeier_stage_df", suffix)
    df_temp <- get(df_name_output)
    for (i in 1:nrow(df_temp)){
      events_reference <- df_temp$n.event[df_temp$time==stage_ref_time]
      events_testgroup <- df_temp[i, "n.event"]
      events  <- c(events_testgroup, events_reference)
      
      time_at_risk_reference <- df_temp$n.risk[df_temp$time==stage_ref_time] * 4
      time_at_risk_testgroup <- df_temp[i, "n.risk"] * 4
      time_at_risk <- c(time_at_risk_testgroup, time_at_risk_reference)
      
      rr_test <- rateratio.test(events, time_at_risk, RR = 1, alternative = "two.sided")
      df_temp[i, "rate_ratio"]  <- rr_test$estimate[1]
      df_temp[i, "lower_95%CI"] <- rr_test$conf.int[1]
      df_temp[i, "upper_95%CI"] <- rr_test$conf.int[2]
      df_temp[i, "p_value"]     <- rr_test$p.value
    }
    
    df_temp$time[df_temp$time == -8] <- "reproductive"
    df_temp$time[df_temp$time ==  0] <- "perimenopause"
    df_temp$time[df_temp$time ==  8] <- "postmenopause"
    
    assign(df_name_output, df_temp)
  }
  
  ## Keep only relevant columns and stages
  for (illness in names(all_illnesses_list)){
    df_name_in  <- paste0(illness, "_kaplanmeier_stage_df", suffix) # input
    df_name_out <- paste0(illness, "_minimal_stage_df", suffix)     # output
    df_temp     <- get(df_name_in)
    
    df_temp <- df_temp %>% filter(time == "reproductive" | time == "perimenopause" | time == "postmenopause")
    df_temp <- select(df_temp, !contains("MANUAL"))
    
    print(paste0(all_illnesses_list[illness], " in ", participant_sex, " participants:"))
    print(df_temp)
    
    assign(df_name_out, df_temp)
  }
  assign(df_name, df)
}
[1] "Major depressive disorder in female participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive  39800     551  1.0000000   0.8870030   1.1273919 1.000000e+00
2 perimenopause  38899     698  1.2961297   1.1574856   1.4519371 5.628249e-06
3 postmenopause  36642     345  0.6800978   0.5927406   0.7794723 1.629452e-08
[1] "Mania in female participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI     p_value
1  reproductive 128105      26  1.0000000   0.5579248    1.792356 1.000000000
2 perimenopause 128051      55  2.1162767   1.3047380    3.515791 0.001677812
3 postmenopause  90300      18  0.9821492   0.5072433    1.861506 1.000000000
[1] "Schizophrenia spectrum disorder in female participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI    p_value
1  reproductive 128170      20  1.0000000   0.5106147   1.9584240 1.00000000
2 perimenopause 128144      19  0.9501928   0.4797830   1.8755778 1.00000000
3 postmenopause 102879       6  0.3737497   0.1228233   0.9649527 0.04050593
[1] "Other disorders in female participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive 127292     211   1.000000   0.8223403    1.216042 1.000000e+00
2 perimenopause 126798     442   2.102948   1.7808432    2.489651 5.905148e-20
3 postmenopause  89053     307   2.079737   1.7396963    2.490059 1.700347e-16
[1] "Depressive symptoms in female participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive 125212     718   1.000000   0.9004671    1.110535 1.000000e+00
2 perimenopause 123607    1346   1.898994   1.7332496    2.081929 9.012984e-46
3 postmenopause  86292     659   1.331792   1.1963421    1.482393 1.395953e-07
[1] "Combined psychiatric disorders in female participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive 123120     753   1.000000   0.9027191    1.107764 1.000000e+00
2 perimenopause 121764    1133   1.521404   1.3862376    1.670489 2.336781e-19
3 postmenopause  95690     637   1.088445   0.9779128    1.211178 1.220218e-01
[1] "Major depressive disorder in male participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive  37719     461   1.000000   0.8769746   1.1402839 1.000000e+00
2 perimenopause  36925     512   1.134511   0.9983997   1.2894596 5.299239e-02
3 postmenopause  34917     311   0.728757   0.6290911   0.8433131 1.629796e-05
[1] "Mania in male participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI    p_value
1  reproductive 128131      42  1.0000000   0.6362608    1.571683 1.00000000
2 perimenopause 128050      37  0.8815096   0.5509870    1.405011 0.65499835
3 postmenopause  90323      18  0.6079657   0.3294131    1.079291 0.09458237
[1] "Schizophrenia spectrum disorder in male participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI   p_value
1  reproductive 128108      21  1.0000000   0.5196358    1.924425 1.0000000
2 perimenopause 128068      12  0.5716070   0.2563663    1.216469 0.1630267
3 postmenopause 100808      11  0.6656633   0.2898435    1.444198 0.3568320
[1] "Other disorders in male participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive 127449     201   1.000000   0.8182974    1.222050 1.000000e+00
2 perimenopause 126994     289   1.442962   1.2010795    1.736284 6.905228e-05
3 postmenopause  89408     192   1.361649   1.1114316    1.667791 2.689628e-03
[1] "Depressive symptoms in male participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive 126547     560   1.000000   0.8878745    1.126285 1.000000e+00
2 perimenopause 125220     923   1.665681   1.4980442    1.853378 4.944643e-22
3 postmenopause  87670     534   1.376430   1.2202595    1.552451 1.644932e-07
[1] "Combined psychiatric disorders in male participants:"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI     p_value
1  reproductive 125218     684  1.0000000   0.8981204    1.113436 1.000000000
2 perimenopause 123938     803  1.1861011   1.0697658    1.315372 0.001116029
3 postmenopause  96176     498  0.9479235   0.8428599    1.065499 0.379747821

Sensitivity analysis

Sensitivity analysis

This code runs the Kaplan-Meier analysis of the combined psychiatric disorders group on subsets of the sample.

Details on the sensitivity analysis can be found in the published supplementary material in Nature Mental Health.

## Townsend deprivation index
# Make column for Townsend numeric
UKBBv8$townsend <- as.numeric(UKBBv8[, TOWNSEND])
# Create subsets of the top and bottom 10%s
n10 <-round(nrow(UKBBv8)/10) # How many people per 10% group
townsend_low  <- UKBBv8 %>% slice_min(townsend, n = n10)  # Subset of bottom 10%
townsend_high <- UKBBv8 %>% slice_max(townsend, n = n10)  # Subset of top 10%

## BMI 
# Create column for BMI as numeric
UKBBv8$bmi      <- as.numeric(UKBBv8[, paste0(BMI, "0.0")])
bmi_underweight <- subset(UKBBv8, UKBBv8$bmi < 18.5)
bmi_healthy     <- subset(UKBBv8, (UKBBv8$bmi >= 18.5) & (UKBBv8$bmi < 25))
bmi_preobese    <- subset(UKBBv8, (UKBBv8$bmi >= 25) & (UKBBv8$bmi < 30))
bmi_obese       <- subset(UKBBv8, UKBBv8$bmi >= 30)

## Smoking status
smoking_status          <- paste0(SMOKE_STAT, "0.0") # Column name for smoking status at initial visit
never_smokers           <- subset(UKBBv8, UKBBv8[, smoking_status] == 0)
previous_smokers        <- subset(UKBBv8, UKBBv8[, smoking_status] == 1)
current_smokers         <- subset(UKBBv8, UKBBv8[, smoking_status] == 2)

## Alcohol intake frequency.
alcohol_freq            <- paste0(ALC_FREQ, "0.0") # Column name for alcohol intake frequency at initial visit
alcohol_daily           <- subset(UKBBv8, UKBBv8[, alcohol_freq] == 1)
alcohol_weekly_3to4     <- subset(UKBBv8, UKBBv8[, alcohol_freq] == 2)
alcohol_weekly_1to2     <- subset(UKBBv8, UKBBv8[, alcohol_freq] == 3)
alcohol_monthly_1to3    <- subset(UKBBv8, UKBBv8[, alcohol_freq] == 4)
alcohol_special_occ     <- subset(UKBBv8, UKBBv8[, alcohol_freq] == 5)
alcohol_never           <- subset(UKBBv8, UKBBv8[, alcohol_freq] == 6)

### Kaplan-Meier (analysis of reproductive stages)
# Create vector of analyses
analyses_vec <- c("townsend_low", "townsend_high",
                  "bmi_underweight", "bmi_healthy", "bmi_preobese", "bmi_obese",
                  "never_smokers", "previous_smokers", "current_smokers",
                  "alcohol_daily", "alcohol_weekly_3to4", "alcohol_weekly_1to2", "alcohol_monthly_1to3", "alcohol_special_occ", "alcohol_never")
## Analyses loop
stage_ref_time <- -8 
sensitivity_analysis_vec <- c("combined")
for (illness in sensitivity_analysis_vec){
  for (group in analyses_vec){
    illness_diagnosed <- paste0(illness, "_diagnosed")
    illness_status    <- paste0(illness, "_status")
    time_to_event     <- paste0("time_to_", illness)
    input_df  <- group
    df_name   <- paste0(group, "_", illness, "_kaplanmeier_stage_df") # Name of output dataframe
    
    # Keep relevant columns
    df <- select(get(input_df), contains(illness))
    df <- subset(df, !(get(illness_status)==0 & get(illness_diagnosed)==1))
    
    df$stage <- NA
    
    for (row in 1:nrow(df)){
      if (df[row, time_to_event] < -10){
        df[row, "stage"] <- -11
        }
      else if (df[row, time_to_event] >= -10 && df[row, time_to_event] <= -6){
        df[row, "stage"] <- -8 # reproductive
      }
      else if (df[row, time_to_event] > -6 && df[row, time_to_event] < -2){
        df[row, "stage"] <- -4
      }
      else if (df[row, time_to_event] >= -2 && df[row, time_to_event] <= 2){
        df[row, "stage"] <- 0 # perimenopause
      }
      else if (df[row, time_to_event] > 2 && df[row, time_to_event] < 6){
        df[row, "stage"] <- 4
      }
      else if (df[row, time_to_event] >= 6 && df[row, time_to_event] <= 10){
        df[row, "stage"] <- 8 # postmenopause
      }
      else if (df[row, time_to_event] > 10){
        df[row, "stage"] <- 11
      }
      else {
        print("Error: time to event variable not classified as a stage")
      }
    }
    ## SET VARIABLES ##
    kaplanmeier_model   <- paste0(group, "_stage_kaplanmeier_model")    ## SET VARIABLE: Model output
    kaplanmeier_summary <- paste0(group, "_stage_kaplanmeier_summary")  ## SET VARIABLE: Model summary output
    ## ANALYSIS ##
    model   <- survfit(Surv(stage, get(illness_status)) ~ 1, data = df) # Create Kaplan-Meier model
    summary <- summary(model)                                           # Create model summary
    df      <- as.data.frame(summary[c("time", "n.risk", "n.event")])                      # Create dataframe, selecting relevant columns
    df$MANUAL_rate_ppy <- df$n.event / (df$n.risk * 4)                                     # Add column for rate per person-year
    df$MANUAL_rr       <- df$MANUAL_rate_ppy / df$MANUAL_rate_ppy[df$time==stage_ref_time] # Add column for rate ratio relative to -10y before FMP
    ## ASSIGNMENTS ##
    assign(kaplanmeier_model, model)
    assign(kaplanmeier_summary, summary)
    assign(df_name, df)
  }
  ## Rate ratio loop
  for (group in analyses_vec){
    df_name   <- paste0(group, "_", illness, "_kaplanmeier_stage_df") # Name of input (and output) dataframe
    df        <- get(df_name)
    for (i in 1:nrow(df)){
      events_reference <- df$n.event[df$time==stage_ref_time]
      events_testgroup <- df[i, "n.event"]
      events  <- c(events_testgroup, events_reference)
      
      time_at_risk_reference <- df$n.risk[df$time==stage_ref_time] * 4
      time_at_risk_testgroup <- df[i, "n.risk"] * 4
      time_at_risk <- c(time_at_risk_testgroup, time_at_risk_reference)
      
      rr_test <- rateratio.test(events, time_at_risk, RR = 1, alternative = "two.sided")
      df[i, "rate_ratio"]  <- rr_test$estimate[1]
      df[i, "lower_95%CI"] <- rr_test$conf.int[1]
      df[i, "upper_95%CI"] <- rr_test$conf.int[2]
      df[i, "p_value"]     <- rr_test$p.value
    }
    
    df$time[df$time == -8] <- "reproductive"
    df$time[df$time ==  0] <- "perimenopause"
    df$time[df$time ==  8] <- "postmenopause"
    
    assign(df_name, df)
  }
  ## Keep only relevant columns and stages
  for (group in analyses_vec){
    df_name_in  <- paste0(group, "_", illness, "_kaplanmeier_stage_df") # input
    df_name_out <- paste0(group, "_", illness, "_minimal_stage_df")     # output
    df          <- get(df_name_in)
    
    df <- df %>% filter(time == "reproductive" | time == "perimenopause" | time == "postmenopause")
    df <- select(df, !contains("MANUAL"))
    
    assign(df_name_out, df)
  }
  
  for (group in analyses_vec){
    print(paste0(group))
    print(get(paste0(group, "_", illness, "_minimal_stage_df")))
  }
}
[1] "townsend_low"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI     p_value
1  reproductive  12328      75   1.000000   0.7163181    1.396028 1.000000000
2 perimenopause  12189     116   1.564304   1.1600531    2.120317 0.002864308
3 postmenopause   9676      63   1.070227   0.7532346    1.516324 0.753205131
[1] "townsend_high"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI    p_value
1  reproductive  12254      74   1.000000   0.7146432    1.399300 1.00000000
2 perimenopause  12136     104   1.419070   1.0432235    1.938593 0.02496374
3 postmenopause   9050      56   1.024674   0.7109169    1.469730 0.95747326
[1] "bmi_underweight"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI    p_value
1  reproductive    981       5  1.0000000   0.2301425    4.345135 1.00000000
2 perimenopause    972      13  2.6240741   0.8779052    9.400926 0.09239907
3 postmenopause    793       3  0.7422446   0.1152645    3.815029 0.96787546
[1] "bmi_healthy"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive  48447     301   1.000000   0.8494973    1.177167 1.000000e+00
2 perimenopause  47923     431   1.447550   1.2464754    1.682782 8.363045e-07
3 postmenopause  37820     255   1.085223   0.9148581    1.286519 3.582408e-01
[1] "bmi_preobese"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive  46334     260   1.000000   0.8388053    1.192172 1.000000e+00
2 perimenopause  45861     439   1.705876   1.4599759    1.996395 5.056622e-12
3 postmenopause  36396     244   1.194710   0.9990740    1.428283 5.122315e-02
[1] "bmi_obese"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI     p_value
1  reproductive  26818     186  1.0000000   0.8116651    1.232035 1.000000000
2 perimenopause  26470     247  1.3454156   1.1077861    1.636282 0.002500621
3 postmenopause  20261     133  0.9464642   0.7518337    1.188781 0.670244008
[1] "never_smokers"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive  72219     390   1.000000   0.8668097    1.153656 1.000000e+00
2 perimenopause  71458     648   1.679233   1.4787215    1.908901 2.661562e-16
3 postmenopause  55745     341   1.132753   0.9766634    1.313296 1.004435e-01
[1] "previous_smokers"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive  40623     269   1.000000   0.8413511    1.188564 1.000000e+00
2 perimenopause  40172     384   1.443536   1.2320129    1.693306 3.942498e-06
3 postmenopause  32533     216   1.002650   0.8343507    1.203758 1.000000e+00
[1] "current_smokers"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI   p_value
1  reproductive   9860      93   1.000000   0.7420485    1.347621 1.0000000
2 perimenopause   9718      99   1.080071   0.8055447    1.449182 0.6445577
3 postmenopause   7063      76   1.140823   0.8312763    1.561505 0.4376114
[1] "alcohol_daily"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive  21999     139  1.0000000   0.7847576    1.274279 1.0000000000
2 perimenopause  21737     209  1.5217203   1.2220707    1.899664 0.0001325585
3 postmenopause  17705     110  0.9832974   0.7586433    1.271888 0.9474333528
[1] "alcohol_weekly_3to4"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI     p_value
1  reproductive  25883     159  1.0000000    0.797578    1.253796 1.000000000
2 perimenopause  25602     227  1.4433427    1.173349    1.778974 0.000423227
3 postmenopause  20112     115  0.9308079    0.725791    1.190675 0.600970175
[1] "alcohol_weekly_1to2"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive  30984     180   1.000000   0.8087955    1.236406 1.000000e+00
2 perimenopause  30673     261   1.464702   1.2067392    1.781006 8.670491e-05
3 postmenopause  23663     155   1.127527   0.9036805    1.405492 2.980092e-01
[1] "alcohol_monthly_1to3"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI     p_value
1  reproductive  15052     112   1.000000   0.7626465    1.311223 1.000000000
2 perimenopause  14861     161   1.455975   1.1369003    1.870018 0.002552083
3 postmenopause  11435      88   1.034243   0.7732550    1.379663 0.866509824
[1] "alcohol_special_occ"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive  17900      93   1.000000   0.7420485    1.347621 1.000000e+00
2 perimenopause  17726     160   1.737318   1.3372108    2.268094 2.143091e-05
3 postmenopause  13966     111   1.529752   1.1508533    2.037247 3.044928e-03
[1] "alcohol_never"
           time n.risk n.event rate_ratio lower_95%CI upper_95%CI      p_value
1  reproductive  11227      68   1.000000   0.7039017    1.420653 1.0000000000
2 perimenopause  11092     113   1.681990   1.2341918    2.307045 0.0007612719
3 postmenopause   8753      58   1.094022   0.7571624    1.576255 0.6774138627

Cleveland dot plots

Cleveland dot plots

Cleveland dot plots used to visualise results from the Kaplan-Meier analysis.

for (df_name in c("UKBBv8", "UKBB_male")) {
  df <- get(df_name)
  ifelse(df_name == "UKBB_male", suffix <- "_male", suffix <- "")
  ifelse(df_name == "UKBB_male", participant_sex <- "male", participant_sex <- "female")
    
  ## Format data frame
  df_list <- c("dp_strict", "bp", "psychosis", "otherillness")
  df_list <- lapply(df_list, paste0, "_minimal_stage_df", suffix)
  # Initialize an empty list to store the modified data frames
  modified_df_list <- list()
  # Loop through the modified_df_list, add a new column with the prefix, and append it to the modified_df_list
  for (df_name_temp in df_list) {
    # Get the data frame from the environment
    df_temp <- get(df_name_temp)
    # Add a new column with the prefix of the data frame name
    df_temp$illness <- sub(paste0("_minimal_stage_df", suffix), "", df_name_temp)
    # Append the modified data frame to the list
    modified_df_list[[df_name_temp]] <- df_temp
  }
  # Merge all the modified data frames together
  cleveland_df <- do.call(rbind, modified_df_list)
  # Rename disorders
  cleveland_df$illness[cleveland_df$illness=="bp"]           <- "Mania"
  cleveland_df$illness[cleveland_df$illness=="dp_strict"]    <- "Major depressive disorder"
  cleveland_df$illness[cleveland_df$illness=="psychosis"]    <- "Schizophrenia spectrum disorders"
  cleveland_df$illness[cleveland_df$illness=="otherillness"] <- "Other diagnoses"
  # Rename columns so ggplot is happy
  colnames(cleveland_df)[colnames(cleveland_df) == "lower_95%CI"] <- "lower_CI"
  colnames(cleveland_df)[colnames(cleveland_df) == "upper_95%CI"] <- "upper_CI"
  # Delete reproductive stage
  cleveland_df <- subset(cleveland_df, time != "reproductive")
  # Rename time stages
  cleveland_df$time[cleveland_df$time=="postmenopause"] <- "Postmenopause"
  cleveland_df$time[cleveland_df$time=="perimenopause"] <- "Perimenopause"
  # Set levels
  cleveland_df$time <- factor(cleveland_df$time, levels = c("Postmenopause", "Perimenopause")) # Reversed because it flips in the plot
  cleveland_df$illness <- factor(cleveland_df$illness, levels = c("Psychiatric disorder", "Major depressive disorder", "Mania", "Schizophrenia spectrum disorders", "Other diagnoses"))
  
  print(paste0("Cleveland plot for ", participant_sex, " participant analysis:"))
  
  ## Create plot
  w <- 0.45
  print(ggplot(cleveland_df, aes(x = illness, y = rate_ratio, color = time, group = interaction(illness, time))) +
    geom_hline(yintercept = 1, linetype = "dashed", color = "grey") +
    geom_point(position = position_dodge(width = w), size=3, preserve = "double") +
    geom_errorbar(aes(ymin = lower_CI, ymax = upper_CI), position = position_dodge(width = w), width = 0.2) +
    geom_line(aes(group = interaction(illness, time)), position = position_dodge(width = w)) +
    labs(x = "", y = "Rate ratio", color = "Time") +
    scale_color_manual(values = c("#FFA6B0", "#31A1AE"), 
                       labels = c( "Postmenopause", "Perimenopause"),
                       guide = guide_legend(title = "Life stage", reverse = TRUE)) +
    scale_x_discrete(limits=rev, labels = function(x) str_wrap(str_replace_all(x, "foo" , " "),
                                                   width = 20)) +
    scale_y_continuous(limits = c(0, 3.75)) +
    coord_flip() +
    theme_classic())
  # Save plot
  ggsave(filename = paste0(PLOT_DIR, "/cleveland" , suffix, ".eps"),
         device = "eps",
         width = 7, height = 6)
}
[1] "Cleveland plot for female participant analysis:"

[1] "Cleveland plot for male participant analysis:"

Onset age plots

Onset age plots

The following plots display the age at onset for each disorder, relative to age at menopause.

# Create vector of disorders to investigate
fmpage_disorders <- list("dp_strict" = "Major depressive disorder", "bp" = "Mania", "psychosis" = "Schizophrenia spectrum disorder", "otherillness" = "Other disorders")

# Set values for the y-axis scale
dp_strict_ymax <- 250
bp_ymax <- 25
psychosis_ymax <- 10
otherillness_ymax <- 140
# Age range investigated
Age <- -10:10

for (df_name in c("UKBBv8", "UKBB_male")) {
  df <- get(df_name)
  ifelse(df_name == "UKBB_male", suffix <- "_male", suffix <- "")
  ifelse(df_name == "UKBB_male", participant_sex <- "male", participant_sex <- "female")

  UKBB_df_temp <- df
  # Loop through each disorder
  for (disorder in names(fmpage_disorders)){
    # Set variable names
    status <- paste0(disorder, "_status")
    diagnosed <- paste0(disorder, "_diagnosed")
    disorder_fmp_age <- paste0(disorder, "_delta")
    ## Create data frame of individuals to include
    # For strict depression, only include those who answered the MHQ
    if (disorder == "dp_strict"){
      df_temp <- subset(UKBB_df_temp, !is.na(UKBB_df_temp[[MHQ_MD_C1]])) # People who answered depression questions
      df_temp <- subset(df_temp, !(get(status)==0 & get(diagnosed)==1)) # Exclude diagnosed but no onset age
    }
    else {
      df_temp <- subset(UKBB_df_temp, !(get(status)==0 & get(diagnosed)==1)) # Exclude diagnosed but no onset age
    }
    table <- data.frame(Age) # Create data frame formatted for ggplot
    table$Incidence <- NA
    for (age in table$Age){
      table$Incidence[table$Age == age] <- nrow(subset(df_temp, df_temp[, disorder_fmp_age] >= (age-0.5) & (df_temp[, disorder_fmp_age] < (age+0.5))))
    }
    assign(paste0(disorder, "_fmp_table"), table)
    print(paste0(fmpage_disorders[[disorder]], " in ", participant_sex, " participants (n=", nrow(df_temp), "): "))
    # Plot
    print(ggplot(table, aes(x=Age, y=Incidence)) +
      geom_bar(stat = "identity", fill = "#98D0D6") +
      geom_vline(xintercept=0, linetype = "dashed", color = "grey") +
      scale_x_continuous(expand = c(0,0), breaks = scales::pretty_breaks(n=10)) +
      scale_y_continuous(expand = c(0,0), limits = c(0, get(paste0(disorder, "_ymax"))), breaks = scales::pretty_breaks(n=6), position = "right") +
      labs(x = "Onset relative to FMP (years)", y = "Number of new onsets") +
      theme_classic())
    # Save plot
    ggsave(filename = paste0(PLOT_DIR, "/", disorder, "_delta", suffix, ".eps"),
           device = "eps",
          width = 3, height = 3)
    assign(paste0(disorder, "_table"), table) # For running loop outside of code chunk (e.g. for bug fixing)
  }
}
[1] "Major depressive disorder in female participants (n=43496): "

[1] "Mania in female participants (n=128291): "

[1] "Schizophrenia spectrum disorder in female participants (n=128280): "

[1] "Other disorders in female participants (n=128238): "

[1] "Major depressive disorder in male participants (n=39485): "

[1] "Mania in male participants (n=128290): "

[1] "Schizophrenia spectrum disorder in male participants (n=128288): "

[1] "Other disorders in male participants (n=128241): "

License

License

© Copyright 2024 Cardiff University. All rights reserved.

                GNU GENERAL PUBLIC LICENSE
                   Version 3, 29 June 2007

Copyright (C) 2007 Free Software Foundation, Inc. https://fsf.org/ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

                        Preamble

The GNU General Public License is a free, copyleft license for software and other kinds of works.

The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program–to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.

To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.

For the developers’ and authors’ protection, the GPL clearly explains that there is no warranty for this free software. For both users’ and authors’ sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.

Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users’ freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.

Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.

The precise terms and conditions for copying, distribution and modification follow.

                   TERMS AND CONDITIONS
  1. Definitions.

“This License” refers to version 3 of the GNU General Public License.

“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.

“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.

To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.

A “covered work” means either the unmodified Program or a work based on the Program.

To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.

To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.

An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.

  1. Source Code.

The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.

A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.

The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.

The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work’s System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.

The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.

The Corresponding Source for a work in source code form is that same work.

  1. Basic Permissions.

All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.

You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.

Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.

  1. Protecting Users’ Legal Rights From Anti-Circumvention Law.

No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.

When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work’s users, your or third parties’ legal rights to forbid circumvention of technological measures.

  1. Conveying Verbatim Copies.

You may convey verbatim copies of the Program’s source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.

You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.

  1. Conveying Modified Source Versions.

You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:

a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.

b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7.  This requirement modifies the requirement in section 4 to
"keep intact all notices".

c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy.  This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged.  This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.

d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.

A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation’s users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.

  1. Conveying Non-Source Forms.

You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:

a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.

b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.

c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source.  This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.

d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge.  You need not require recipients to copy the
Corresponding Source along with the object code.  If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source.  Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.

e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.

A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.

A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.

“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.

If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).

The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.

Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.

  1. Additional Terms.

“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.

When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.

Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:

a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or

b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or

c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or

d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or

e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or

f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.

All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.

If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.

Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.

  1. Termination.

You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).

However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.

Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.

Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.

  1. Acceptance Not Required for Having Copies.

You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.

  1. Automatic Licensing of Downstream Recipients.

Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.

An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party’s predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.

You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.

  1. Patents.

A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor’s “contributor version”.

A contributor’s “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.

Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor’s essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.

In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.

If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient’s use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.

If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.

A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.

Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.

  1. No Surrender of Others’ Freedom.

If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.

  1. Use with the GNU Affero General Public License.

Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.

  1. Revised Versions of this License.

The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.

If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Program.

Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.

  1. Disclaimer of Warranty.

THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  1. Limitation of Liability.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

  1. Interpretation of Sections 15 and 16.

If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.

                 END OF TERMS AND CONDITIONS

        How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.

<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year>  <name of author>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:

<program>  Copyright (C) <year>  <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.

The hypothetical commands show w' andshow c’ should show the appropriate parts of the General Public License. Of course, your program’s commands might be different; for a GUI interface, you would use an “about box”.

You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see https://www.gnu.org/licenses/.

The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read https://www.gnu.org/licenses/why-not-lgpl.html.