Exercise on reproducibility

Back to the main page

Reproducibility

The tab Exercise introduction explains the datasets, please read it carefully. Then proceed to the Questions tab and answer the questions.

You have taken part in a validation study of the Oswestry Disability Index (ODI) in patients with chronic low back pain. Before applying the index in a clinical trial, you want to examine its reproducibility.

As part of the validation, a test–retest study was conducted with 150 patients recruited from both the primary care sector (medical doctors, physiotherapists, chiropractors) and the secondary care sector (an outpatient spine unit). The retest interval was approximately two weeks. Since the patients were on a waiting list during this period, their level of back pain–related disability was considered stable.

The ODI

The ODI includes 10 items, each addressing a daily activity such as pain intensity, personal care, lifting, walking, sitting, standing, sleeping, sex life, social life, and travelling. For each item, the respondent selects one of six statements, scored from 0 to 5, with higher scores indicating greater disability. The item scores are summed and then converted to a percentage score ranging from 0 to 100 by dividing the total score by the maximum possible score (adjusted for the number of items completed).

The Danish version of ODI can be found here

The dataset

The exercise is based on a dataset named osw_reprod_10items.rds. It includes a patient ID number, the 10 ODI items recorded at baseline and again at two-week follow-up, as well as the total ODI scores for each time point.

The variable names follow this structure

  • osw1 = item 1
  • _1 = baseline (time 1, t1)
  • _2 = follow-up (time 2, t2)

The dataset structure is shown in Table 1.

Code
reprod_data <- readRDS(here("files", "02_advanced_course", "day2", "exercises", "reproducibility", "Synthetic data", "osw_reprod_10items.rds"))
  
# Skal ændres når overføres til hjemmesiden

reprod_data |>
  slice_head(n = 6) |>                     # show first 6 rows
  gt() |>
  tab_header(
    title = "Table 1. First 6 lines of the dataset"
  ) |> 
  cols_align(
    align = "center",
    columns = everything()) |>             # center short numbers
  cols_width(everything() ~ px(28)) |>     # narrow columns
  tab_options(
    table.font.size      = px(10),         # smaller font; try 9–11 px
    data_row.padding     = px(1),          # tight row padding
    column_labels.padding= px(2),
    table.width          = pct(100),       # use full content width
    heading.align = "left"
  )
Table 1. First 6 lines of the dataset
patient Pain intensity (t1) Personal care (t1) Lifting (t1) Walking (t1) Sitting (t1) Standing (t1) Sleeping (t1) Sexlife (if applicable) (t1) Social life (t1) Travelling (t1) Pain intensity (t2) Personal care (t2) Lifting (t2) Walking (t2) Sitting (t2) Standing (t2) Sleeping (t2) Sexlife (if applicable) (t2) Social life (t2) Travelling (t2) Total ODI score (baseline) Total ODI score (follow-up)
1 0 2 NA 0 1 2 0 0 1 1 0 2 1 1 1 2 1 1 1 1 16 22
2 1 3 2 1 1 1 0 0 1 2 1 2 1 1 3 2 NA 1 2 2 24 33
3 2 3 3 1 3 2 2 3 2 2 3 4 3 3 2 4 3 3 2 2 46 58
4 1 2 2 1 2 3 NA 1 2 1 2 2 2 2 3 3 2 2 3 2 33 46
5 3 2 1 2 2 2 0 2 2 2 2 2 2 2 2 3 2 2 2 2 36 42
6 1 2 0 2 3 4 2 2 2 3 2 3 3 2 2 3 2 2 3 2 42 48

The variables are summarised below:

Code
# This is for showing a summary of the dataset

skim(reprod_data)
Data summary
Name reprod_data
Number of rows 150
Number of columns 23
_______________________
Column type frequency:
numeric 23
________________________
Group variables None

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
patient 0 1.00 75.50 43.45 1 38.25 75.5 112.75 150 ▇▇▇▇▇
osw1_1 5 0.97 1.25 1.00 0 1.00 1.0 2.00 5 ▇▃▁▁▁
osw2_1 5 0.97 1.81 1.09 0 1.00 2.0 2.00 5 ▇▇▃▁▁
osw3_1 5 0.97 1.45 1.04 0 1.00 1.0 2.00 5 ▇▃▂▁▁
osw4_1 5 0.97 1.06 1.10 0 0.00 1.0 2.00 5 ▇▂▁▁▁
osw5_1 5 0.97 1.60 1.08 0 1.00 2.0 2.00 5 ▇▅▂▁▁
osw6_1 5 0.97 2.01 1.03 0 1.00 2.0 3.00 5 ▆▇▃▂▁
osw7_1 5 0.97 1.12 1.08 0 0.00 1.0 2.00 5 ▇▃▁▁▁
osw8_1 5 0.97 1.23 0.93 0 1.00 1.0 2.00 4 ▅▇▅▂▁
osw9_1 5 0.97 1.50 1.09 0 1.00 1.0 2.00 4 ▅▇▆▂▁
osw10_1 5 0.97 1.43 0.95 0 1.00 1.0 2.00 4 ▂▇▅▂▁
osw1_2 9 0.94 1.74 0.97 0 1.00 2.0 2.00 5 ▇▆▃▁▁
osw2_2 9 0.94 2.26 0.95 0 2.00 2.0 3.00 5 ▅▇▅▂▁
osw3_2 9 0.94 1.83 0.97 0 1.00 2.0 2.00 4 ▁▇▇▃▁
osw4_2 9 0.94 1.62 1.01 0 1.00 2.0 2.00 5 ▇▅▂▁▁
osw5_2 9 0.94 2.14 0.96 0 1.00 2.0 3.00 5 ▅▇▅▁▁
osw6_2 9 0.94 2.65 0.92 1 2.00 3.0 3.00 5 ▂▇▆▃▁
osw7_2 9 0.94 1.64 0.95 0 1.00 2.0 2.00 4 ▂▇▇▂▁
osw8_2 9 0.94 1.72 0.92 0 1.00 2.0 2.00 5 ▇▆▂▁▁
osw9_2 9 0.94 2.00 0.91 0 1.00 2.0 3.00 5 ▅▇▅▁▁
osw10_2 9 0.94 1.96 0.96 0 1.00 2.0 3.00 5 ▆▇▃▁▁
osw_total_1 0 1.00 28.97 15.36 2 18.00 28.0 38.00 87 ▅▇▃▁▁
osw_total_2 0 1.00 39.25 16.38 8 26.00 39.0 49.75 86 ▃▇▇▃▁

Start with the questions in tab ‘1. Correlation coefficient’ and, when finished, continue to the next.

Please write your answers to the questions either in a Word document or on paper. The exercise including answers can be downloaded after the course when activated.

The first thing you do is to calculate the Pearson’s correlation coefficient between the ODI sumscores of t1 and t2. The results are found in Table 2 and visualised in Figure 1.

Code
# Selecting t1 and t2 total scores
corr <- reprod_data |> 
  select(osw_total_1, osw_total_2)

# Pearson's correlation
pcorr <- cor.test(corr$osw_total_1, corr$osw_total_2, method = "pearson", use = "complete.obs") 

# Tidy the correlation test result
pcorr_tidy <- tidy(pcorr) |> 
  select(estimate, statistic, p.value, conf.low, conf.high)

# Create a GT table
pcorr_table <- pcorr_tidy |>
  gt() |>
  tab_header(
    title = "Table 2. Correlation between ODI scores at time 1 and 2"
  ) |>
  fmt_number(
    columns = c(estimate, statistic, p.value, conf.low, conf.high),
    decimals = 2
  ) |>
    cols_merge(
      columns = c(conf.low, conf.high),
      pattern = "({1}; {2})"
      ) |> 
  cols_label(
    estimate = "Pearson CC",
    statistic = "t-statistic",
    p.value = "p-value",
    conf.low = "CI"
  ) |> 
  cols_align(align = "center", 
             columns = everything()
             )
pcorr_table
Table 2. Correlation between ODI scores at time 1 and 2
Pearson CC t-statistic p-value CI
0.94 32.64 0.00 (0.91; 0.95)
Code
# Generating a scatter plot

plot_dat <- reprod_data |>
  filter(!is.na(osw_total_1), !is.na(osw_total_2))

# prepare a concise subtitle using your test results
r_lab  <- sprintf("r = %.2f", pcorr_tidy$estimate)
ci_lab <- sprintf("95%% CI %.2f–%.2f", pcorr_tidy$conf.low, pcorr_tidy$conf.high)
n_cc   <- nrow(plot_dat)

cor_plot <- ggplot(plot_dat, aes(x = osw_total_1, y = osw_total_2)) +
  geom_point(alpha = 0.4, color = "blue") +                    # observed pairs
  geom_abline(slope = 1, intercept = 0, linetype = "dashed") +  # identity line
  scale_x_continuous(limits = c(0, 100)) +                    # x-axis 0–100
  scale_y_continuous(limits = c(0, 100)) +                    # y-axis 0–100
  labs(
    title = "Figure 1. Scatter plot of ODI scores at t1 and t2",
    subtitle = paste(r_lab, " | ", ci_lab, sprintf("| n = %d", n_cc)),
    x = "t1 ODI scores",
    y = "t2 ODI scores"
  ) +
  theme_classic() +                                          # clean base
  theme(
    axis.line = element_line(color = "black"),               # black axes
    axis.ticks = element_line(color = "black"),              # black ticks
    panel.grid = element_blank(),                            # remove gridlines
    axis.text = element_text(color = "black"),               # black labels
    axis.title = element_text(color = "black")
  )
cor_plot

Questions

1.1 What is the Pearson’s correlation coefficient and the associated p-value?

1.2 Discuss what the correlation coefficient tell us about the reliability between the two measurements?

1.3 Explain what the p-value means?

You now want to have a look at the intra-class correlation coefficients (ICC) and standard error of the measurements (SEM) for the measurements. The ICC’s are presented as the output you will get when using the psych package.

Code
# Run ICC using matrix
icc_data <- as.matrix(corr)                   # psych::ICC wants matrix or data.frame
icc_out  <- psych::ICC(icc_data, lmer = TRUE) # includes $results and variance comps

icc_out
Call: psych::ICC(x = icc_data, lmer = TRUE)

Intraclass correlation coefficients 
                         type  ICC    F df1 df2       p lower bound upper bound
Single_raters_absolute   ICC1 0.75  7.1 149 150 3.5e-29       0.673        0.81
Single_random_raters     ICC2 0.77 29.8 149 149 2.7e-69      -0.055        0.93
Single_fixed_raters      ICC3 0.94 29.8 149 149 2.7e-69       0.911        0.95
Average_raters_absolute ICC1k 0.86  7.1 149 150 3.5e-29       0.805        0.90
Average_random_raters   ICC2k 0.87 29.8 149 149 2.7e-69      -0.116        0.96
Average_fixed_raters    ICC3k 0.97 29.8 149 149 2.7e-69       0.954        0.98

 Number of subjects = 150     Number of Judges =  2
See the help file for a discussion of the other 4 McGraw and Wong estimates,

Questions

2.1 Explain which coefficients should be used in a test-retest situation in the output from the psych package. You are welcome to use the teaching material (vodcast or PowerPoint pdf), the psych ICC help file in R if you have it installed, or chatGPT/Perplexity/Copilot or the like.

2.2 What do you think about the reliability (remember ICC2 = ICC(A,1) and ICC3 = ICC(C,1))?

Next, you turn to looking at the variance components of a repeated measures ANOVA. You want to calculate ICC (reliability) and SEM (measurement error) using the values in Table 4.

Code
# We use the data.frame 'icc_results' and extract the variance components from the ICC calculations in psych

# Generating tibble with variance components
icc_variance <- icc_out[["lme"]] |> 
  rownames_to_column(var = "variance_component") |> 
  select(-Percent) |> 
  as_tibble() |> 
  mutate(across(where(is.numeric), ~round(., 3))) |> 
  mutate(variance_component = recode(variance_component, 
                                     "ID" = "Patients", 
                                     "Items" = "Time points"))

# Generating Table 2 with variance components

table4 <- gt(icc_variance) |> 
  cols_align(
    align = "center",
    columns = variance
  ) |> 
  tab_header(
    title = md("**Table 4. Variance components**")
  ) |> 
  opt_align_table_header(
    align = "left"
  ) |> 
   cols_label(
    variance_component = "Variance components",
    variance = "Variance"
  ) |> 
  tab_options(
    table.font.size = px(14),
    table.align = "center",
    table.border.top.color = "transparent", # Remove top border around table
     data_row.padding = px(3) # Reduce the height of rows
  )
table4
Table 4. Variance components
Variance components Variance
Patients 235.679
Time points 52.725
Residual 16.363
Total 304.767

Question

2.3 Using the variance estimates, please calculate ICC(C,1), ICC(A,1), SEMconsistency, and SEMagreement.

2.4 What do you think about the measurement error?

Next, examine systematic and random error using the Bland–Altman limits of agreement (LoA). As a first step, review the descriptive statistics for ODI totals at baseline (t1) and two-week follow-up (t2) in Table 5.

Code
odi_summary_dta <- reprod_data |>
  mutate(osw_ch = osw_total_2 - osw_total_1) |> 
  select(osw_total_1, osw_total_2, osw_ch) |>
  pivot_longer(
    everything(),
    names_to  = "time",                # osw_total_1 / osw_total_2 -> "t1"/"t2"
    values_to = "total"
  ) |>
  mutate(time = recode(time, 
                       osw_total_1 = "t1", 
                       osw_total_2 = "t2",
                       osw_ch = "Difference"),
         time = factor(time, levels = c("t1", "t2", "Difference"))) |>
  group_by(time) |>
  summarise(
    n    = sum(!is.na(total)),         # number of non-missing totals
    mean = mean(total, na.rm = TRUE),  # mean at that time
    sd   = sd(total,   na.rm = TRUE),  # SD at that time
    .groups = "drop"
  )

# gt-table

odi_summary_tbl <- gt(odi_summary_dta) |>
  tab_header(
    title = md("**Table 5. Descriptive statistics for the ODI**")
  ) |>
  cols_label(
    time = "Time",
    n    = "n",
    mean = "Mean",
    sd   = "SD"
  ) |>
  fmt_number(columns = c(mean, sd), decimals = 2) |>
  cols_align(align = "center", columns = everything()) |>
  tab_options(
    table.font.size = px(14),
    data_row.padding = px(3),
    table.align = "center"
  ) |>
  tab_source_note(
    source_note = "ODI scores are on a 0–100 scale, 'Difference' represents follow-up (t2) minus baseline (t1)."
  )

odi_summary_tbl
Table 5. Descriptive statistics for the ODI
Time n Mean SD
t1 150 28.97 15.36
t2 150 39.25 16.38
Difference 150 10.28 5.72
ODI scores are on a 0–100 scale, 'Difference' represents follow-up (t2) minus baseline (t1).
Code
# Values for LOA calculations

# Q 3.2
loa_mean <- round(odi_summary_dta$mean[odi_summary_dta$time == "Difference"], 2)
loa_sd <- round(odi_summary_dta$sd[odi_summary_dta$time == "Difference"], 2)
loa <- round(1.96 * odi_summary_dta$sd[odi_summary_dta$time == "Difference"], 2)
loa_lower <- (loa_mean - loa)
loa_upper <- (loa_mean + loa)

# Q 3.4
t1_mean <- round(odi_summary_dta$mean[odi_summary_dta$time == "t1"], 2)
t2_mean_20 <- (t1_mean + 20)
loa_lower_20 <- round(20 - (1.96 * odi_summary_dta$sd[odi_summary_dta$time == "Difference"]), 2)
loa_upper_20 <- round(20 + (1.96 * odi_summary_dta$sd[odi_summary_dta$time == "Difference"]), 2)

Questions

3.1 What is the systematic difference? Which time-point has the highest average?

3.2 What are the LOA’s (limits of agreement)?

3.3 What will happen with ICCconsistency and ICCagreement if time 2 always measures 20 points higher compared to time 1?

3.4 What will happen to the “limits of agreement”?

You now generate a Bland & Altman Limits of agreement plot of the data. The plot is presented in Figure 2.

Code
# --- Prepare BA data (pairwise complete cases)
ba_dta <- reprod_data |>
  transmute(
    mean = (osw_total_1 + osw_total_2) / 2,   # mean of the two totals
    diff =  osw_total_2 - osw_total_1         # t2 - t1 (systematic difference)
  ) |>
  drop_na()

# --- BA plot stats
n_ba     <- nrow(ba_dta)
mdiff    <- mean(ba_dta$diff)                     # mean difference
sd_diff  <- sd(ba_dta$diff)                       # SD of differences
loa_low  <- mdiff - 1.96 * sd_diff            # lower LoA
loa_high <- mdiff + 1.96 * sd_diff            # upper LoA

# --- 95% CIs for LOA

se_mdiff <- sd_diff / sqrt(n_ba)
se_loa <- sd_diff * sqrt(1/n_ba + (1.96^2)/(2*(n_ba - 1)))
mdiff_ci <- c(mdiff - 1.96 * se_mdiff, mdiff + 1.96 * se_mdiff)
loa_low_ci  <- c(loa_low  - 1.96 * se_loa, loa_low  + 1.96 * se_loa)
loa_high_ci <- c(loa_high - 1.96 * se_loa, loa_high + 1.96 * se_loa)

# --- Bland–Altman plot

ba_plot <- ggplot(ba_dta, aes(x = mean, y = diff)) +
  geom_point(alpha = 0.6, color = "steelblue") +         # data points
  geom_hline(yintercept = mdiff, linewidth = 0.6, color = "red") +   # mean diff
  geom_hline(yintercept = loa_low,linetype = "dashed") +
  geom_hline(yintercept = loa_high, linetype = "dashed") +
  geom_hline(yintercept = 0, linewidth = 0.6) +
  # labels on the right margin
  annotate("text", x = Inf, y = mdiff,
           label = paste0("Mean diff. = ", sprintf("%.2f", mdiff)),
           hjust = 1.02, vjust = -0.4, size = 3.5) +
  annotate("text", x = Inf, y = loa_high,
           label = paste0("Upper LoA = ", sprintf("%.2f", loa_high)),
           hjust = 1.02, vjust = -0.4, size = 3.5) +
  annotate("text", x = Inf, y = loa_low,
           label = paste0("Lower LoA = ", sprintf("%.2f", loa_low)),
           hjust = 1.02, vjust = 1.4, size = 3.5) +
  scale_x_continuous(
    limits = c(0, 100),
    breaks = seq(0, 100, by = 10)
    ) + 
  labs(
    title = "Figure 2. Bland–Altman plot of the ODI",
    x = "Mean ODI score of t1 and t2 (0-100)",
    y = "Difference in ODI score (t2 − t1)"
  ) +
  theme_classic() +                                      # clean look: black axes, no grid
  theme(
    axis.line  = element_line(color = "black"),
    axis.ticks = element_line(color = "black"),
    axis.text  = element_text(color = "black"),
    axis.title = element_text(color = "black")
  )
ba_plot

3.5 What does Figure 2 show, and how should it be interpreted?

In a study by De Winter et al. (2004), two physiotherapists measured shoulder abduction (Figure 1) in 155 patients with unilateral shoulder pain using an electronic inclinometer (Figure 2). The outcome is the abduction angle in degrees.

Figure 3. Shoulder abduction

Figure 4. Inclinometer measuring the abduction angle

Table 6 reproduces their inter-rater reliability results for the painful and contralateral healthy shoulder.

Code
dewinter_agree <- data.frame(
  Condition = c("Painful shoulder", "Healthy shoulder"),
  PhysA_Mean_SD = c("69.5 (17.6)", "79.8 (7.6)"),
  PhysB_Mean_SD = c("68.8 (16.3)", "78.9 (8.4)"),
  Mean_Diff_A_B_SD = c("0.8 (10.0)", "0.9 (9.6)"),
  Agreement_less_5 = c("43%", "43%"),
  Agreement_less_10 = c("72%", "72%"),
  ICC = c(0.83, 0.28)
)

# Generate the table using gt
(table4 <- dewinter_agree |>
  gt() |>
  tab_header(
    title = md("**Table 6. Inter-rater reliability results**")
  ) |>
  cols_label(
    PhysA_Mean_SD = "Phys A (Mean (SD))",
    PhysB_Mean_SD = "Phys B (Mean (SD))",
    Mean_Diff_A_B_SD = "Mean diff. A-B (SD)",
    Agreement_less_5 = "< 5° Agreement",
    Agreement_less_10 = "< 10° Agreement",
    ICC = "ICC"
  ) |>
  fmt_number(
    columns = c(ICC),
    decimals = 2
  ) |>
    cols_align(
    align   = "center",
    columns = -1          # all columns except the first
  ) |> 
  tab_options(
    table.font.size = "small",
    table.width = pct(100)
  ))
Table 6. Inter-rater reliability results
Condition Phys A (Mean (SD)) Phys B (Mean (SD)) Mean diff. A-B (SD) < 5° Agreement < 10° Agreement ICC
Painful shoulder 69.5 (17.6) 68.8 (16.3) 0.8 (10.0) 43% 72% 0.83
Healthy shoulder 79.8 (7.6) 78.9 (8.4) 0.9 (9.6) 43% 72% 0.28

Questions

4.1 Despite identical “within-tolerance” agreement (43% within \(\pm\) 5° and 72% within \(\pm\) 10°) for both shoulders, the ICC differs markedly (0.83 vs 0.28). Why? What does this tell you about ICC?

4.2 Discuss which parameter is preferrable for judging inter-rater reliability here?

Now we turn to the individual items of the ODI. The questionnaire has 10 items and you calculate the different kappa values (\(\kappa\)) of all 10 items. The results are shown in Table 5.

Code
# --- FUNCTION
# Computes unweighted kappa, quadratic-weighted kappa (Fleiss–Cohen),
# Brennan–Prediger kappa, and observed agreement for one item.
# 'item' must match the column name stem (e.g., "osw1" -> uses osw1_1 and osw1_2)

# Compute unweighted kappa, weighted (Fleiss–Cohen) kappa, Brennan–Prediger kappa
# + their 95% CIs (BP via Wilson CI on Po), and observed agreement.
# item must be the stem, e.g. "osw1" (expects columns osw1_1 and osw1_2).

calc_item_kappas <- function(dat, item, item_levels = 0:5, conf.level = 0.95) {
  # build expected column names
  c1 <- paste0(item, "_1")
  c2 <- paste0(item, "_2")
  if (!all(c(c1, c2) %in% names(dat))) {
    stop("Columns ", c1, " and/or ", c2, " not found in 'dat'.")
  }

  # keep complete pairs; weight definitions need common ordered levels
  pairs <- dat |>
    select(all_of(c(c1, c2))) |>
    drop_na()

  # if no data to compute on, return NA row (fail gracefully)
  if (nrow(pairs) == 0L) {
    return(tibble(
      item                        = item,
      kappa_unweighted            = NA_real_,
      kappa_unweighted_l95        = NA_real_,
      kappa_unweighted_u95        = NA_real_,
      kappa_weighted              = NA_real_,
      kappa_weighted_l95          = NA_real_,
      kappa_weighted_u95          = NA_real_,
      brennan_prediger            = NA_real_,
      brennan_prediger_l95        = NA_real_,
      brennan_prediger_u95        = NA_real_,
      observed_agreement          = NA_real_
    ))
  }

  # coerce to same ordered factor levels (ensures a square table incl. empty cats)
  t1 <- factor(pairs[[c1]], levels = item_levels, ordered = TRUE)
  t2 <- factor(pairs[[c2]], levels = item_levels, ordered = TRUE)

  # confusion matrix
  tab <- table(t1, t2)

  # kappa (DescTools returns a named numeric vector)
  k_unw <- DescTools::CohenKappa(tab, weights = "Unweighted",   conf.level = conf.level)
  k_wsq <- DescTools::CohenKappa(tab, weights = "Fleiss-Cohen", conf.level = conf.level)

  # observed agreement Po
  A  <- sum(diag(tab))      # exact agreements
  n  <- sum(tab)            # number of paired ratings
  po <- A / n

  # Brennan–Prediger (Prediger) kappa and its CI via linear transform of Po CI
  k_cat <- length(item_levels)             # intended #categories (stable even if some unused)
  a <- k_cat / (k_cat - 1)                 # slope of linear transform
  b <- -1 / (k_cat - 1)                    # intercept
  bp <- a * po + b                         # point estimate

  # Wilson CI for Po, then transform endpoints to BP CI
  po_ci <- DescTools::BinomCI(A, n, conf.level = conf.level, method = "wilson")
  bp_l  <- a * po_ci[, "lwr.ci"] + b
  bp_u  <- a * po_ci[, "upr.ci"] + b
  
  # clip to [-1,1] just in case of numerical edge cases
  bp_l  <- pmax(-1, bp_l)
  bp_u  <- pmin( 1, bp_u)

  tibble(
    item                        = item,
    kappa_unweighted            = unname(k_unw["kappa"]),
    kappa_unweighted_l95        = unname(k_unw["lwr.ci"]),
    kappa_unweighted_u95        = unname(k_unw["upr.ci"]),
    kappa_weighted              = unname(k_wsq["kappa"]),
    kappa_weighted_l95          = unname(k_wsq["lwr.ci"]),
    kappa_weighted_u95          = unname(k_wsq["upr.ci"]),
    brennan_prediger            = as.numeric(bp),
    brennan_prediger_l95        = as.numeric(bp_l),
    brennan_prediger_u95        = as.numeric(bp_u),
    observed_agreement          = po
  )
}


# --- USAGE

items <- paste0("osw", 1:10)                       # osw1 ... osw10
item_levels <- 0:5                                  # osw levels

kappa_tbl_all <- map_dfr(
  items,
  ~ calc_item_kappas(reprod_data, .x, item_levels = item_levels, conf.level = 0.95)
) |>
  mutate(across(where(is.numeric), ~ round(.x, 2))) |>
  arrange(parse_number(item))

# --- Generating gt table

kappa_gt <- kappa_tbl_all |>
  gt() |> 
  cols_merge(
    columns = c(kappa_unweighted_l95, kappa_unweighted_u95),
    pattern = "({1}; {2})"
  ) |>
  cols_merge(
    columns = c(kappa_weighted_l95, kappa_weighted_u95),
    pattern = "({1}; {2})"
  ) |>
  cols_merge(
    columns = c(brennan_prediger_l95, brennan_prediger_u95),
    pattern = "({1}; {2})"
  ) |> 
  cols_label(
    item                   = "Item",
    kappa_unweighted       = "Kappa",
    kappa_unweighted_l95   = "95% CI",
    kappa_weighted         = "Kappa",
    kappa_weighted_l95     = "95% CI",
    brennan_prediger       = "Brennan–Prediger",
    brennan_prediger_l95   = "95% CI",
    observed_agreement     = "Obs. agreement (%)"
  ) |>
  # (optional) add spanners to visually group estimate + CI pairs
  tab_spanner("Unweighted", columns = c(kappa_unweighted, kappa_unweighted_l95)) |>
  tab_spanner("Weighted", columns = c(kappa_weighted, kappa_weighted_l95)) |>
  tab_spanner("Brennan–Prediger", columns = c(brennan_prediger, brennan_prediger_l95)) |>
  cols_align(align = "center", columns = -item) |>
  tab_header(title = md("**Table 5. Kappa estimates for the ODI items**")) |>
  tab_options(
    table.font.size = px(12),
    heading.title.font.size = px(14),
    column_labels.font.size = px(12),
    heading.align = "left") |> 
  tab_footnote(
    footnote = "Brennan & Prediger is similar to PABAK for polytomous items.",
    locations = cells_column_labels(columns = "brennan_prediger")
  ) |> 
  tab_footnote(
    footnote = "Quadratic weights (Fleiss-Cohen)",
    locations = cells_column_labels(columns = "kappa_weighted")
  )

kappa_gt
Table 5. Kappa estimates for the ODI items
Item
Unweighted
Weighted
Brennan–Prediger
Obs. agreement (%)
Kappa 95% CI Kappa1 95% CI Brennan–Prediger2 95% CI
osw1 0.05 (-0.05; 0.16) 0.56 (0.44; 0.67) 0.17 (0.08; 0.27) 0.31
osw2 0.13 (0.03; 0.24) 0.46 (0.32; 0.60) 0.23 (0.14; 0.33) 0.36
osw3 0.22 (0.11; 0.33) 0.52 (0.39; 0.66) 0.31 (0.22; 0.41) 0.43
osw4 0.10 (0.00; 0.19) 0.54 (0.44; 0.65) 0.17 (0.08; 0.27) 0.31
osw5 0.21 (0.11; 0.32) 0.55 (0.44; 0.66) 0.30 (0.20; 0.40) 0.42
osw6 0.16 (0.06; 0.27) 0.43 (0.30; 0.57) 0.26 (0.17; 0.36) 0.38
osw7 0.13 (0.02; 0.23) 0.47 (0.34; 0.60) 0.21 (0.13; 0.31) 0.35
osw8 0.30 (0.19; 0.41) 0.43 (0.27; 0.59) 0.41 (0.31; 0.51) 0.51
osw9 0.24 (0.13; 0.34) 0.53 (0.42; 0.64) 0.31 (0.22; 0.41) 0.43
osw10 0.18 (0.07; 0.28) 0.50 (0.37; 0.62) 0.28 (0.18; 0.38) 0.40
1 Quadratic weights (Fleiss-Cohen)
2 Brennan & Prediger is similar to PABAK for polytomous items.
Code
# ----- Generating table for osw1 only with all relevant values (used to generate function)

# # Item levels
# item_levels <- 0:5
# 
# # Matrix of osw1 as factors
# tab_osw1 <- reprod_data |>
#   select(osw1_1, osw1_2) |>
#   drop_na() |>
#   mutate(across(everything(),
#                 ~ factor(.x, levels = item_levels, ordered = TRUE))) |>
#   with(table(osw1_1, osw1_2))
# 
# # Kappa unweighted
# res_unw <- CohenKappa(tab_osw1, weights = "Unweighted",  conf.level = 0.95)
# 
# # Kappa weighted (quadratic)
# res_wsq <- DescTools::CohenKappa(tab_osw1, weights = "Fleiss-Cohen", conf.level = 0.95)
# 
# # Observed agreement & BP (Prediger) kappa (+ its CI)
# A  <- sum(diag(tab_osw1))                              # exact agreements
# n  <- sum(tab_osw1)                                    # total paired ratings
# po <- A / n                                            # observed agreement
# 
# k  <- nrow(tab_osw1)                                   # number of categories (should be 6)
# a  <- k / (k - 1)                                      # linear transform slope
# b  <- -1 / (k - 1)                                     # linear transform intercept
# 
# bp_kappa <- a * po + b                                 # BP point estimate
# 
# # CI for Po (Wilson), then transform endpoints to BP CI
# po_ci  <- DescTools::BinomCI(A, n, conf.level = 0.95, method = "wilson")
# bp_l95 <- a * po_ci[, "lwr.ci"] + b
# bp_u95 <- a * po_ci[, "upr.ci"] + b
# 
# bp_l95 <- pmax(-1, bp_l95) # clip to valid range
# bp_u95 <- pmin( 1, bp_u95)
# 
# # A table with all kappa values and observed agreement
# kappa_tbl <- tibble(
#   item                 = "osw1",
#   kappa_unweighted     = unname(res_unw["kappa"]),
#   kappa_weighted       = unname(res_wsq["kappa"]),   # quadratic (Fleiss–Cohen)
#   brennan_prediger     = bp_kappa,
#   observed_agreement   = po
# ) |>
#   mutate(across(where(is.numeric), ~ round(.x, 3)))
# 
# kappa_tbl

Questions

5.1 Table 5 shows both unweighted and weighted \(\kappa\) (with 95% confidence intervals) for the ODI items. Which version of \(\kappa\) is most appropriate to report in this case, and why?

5.2 Compare weighted and unweighted \(\kappa\) of item 1 (Pain intensity) and item 8 (Sex life, if relevant). Why do their (\(\kappa\)) estimates differ, and why do the weighted and unweighted versions behave differently?

Re-read the item wording and the study design in the exercise introduction.

5.3 In Table 5, item 1 (Pain intensity) shows a very low unweighted \(\kappa\) with a modest observed agreement (~31%). Explain why this can happen for an ordinal 0–5 item, and how Brennan–Prediger \(\kappa\) helps interpret the result.

5.4 How should you report your \(\kappa\) estimates?

A researcher plans a test–retest reproducibility study. She’s been told that reliability “improves” with a more heterogeneous sample, so she intends to include very different patients.

Question

6.1 Is this a sound strategy? Discuss briefly.

To download the answers provided to this exercise you need to open the html-file with the answers - see instructions in that file.

You can download the ‘osw_reprod_10items.rds’ dataset here:

(right-click the link and choose ‘Save as’)

To import it into R use the code below. R-code is provided throughout the exercise:

Code
reprod_data <- read_rds("osw_reprod_10items.rds")

The R libraries used are these:

Code
library(knitr)      # For knitting nice html-files
library(tidyverse)  # For tidy data wrangling and more
library(broom)      # Turning output into tidy tibbles
library(gt)         # For tables
library(gtExtras)   # For tables - extra
library(psych)      # For reliability, ICC, Kappa and much more
library(DescTools)  # Used for Kappa, PABAK and CI's
library(here)       # For locating root folder
library(skimr)      # For skimming dataset