# Load the vcd library for Cohen's Kappa and Weighted Kappa calculation
# If not installed, run: install.packages("vcd")
library(vcd)

# Create the 5x5 contingency matrix based on the provided table data
# Rows: Method II (None, Mild, Moderate, Severe, Extreme)
# Columns: Method I (None, Mild, Moderate, Severe, Extreme)
data_matrix <- matrix(
  c(89,  5, 16,  2,  4,   # None (Method II)
    36,  3, 15,  6,  2,   # Mild (Method II)
    20,  4, 22,  6,  1,   # Moderate (Method II)
    14,  2, 37, 18, 16,   # Severe (Method II)
     4,  1, 16, 23, 50),  # Extreme (Method II)
  nrow = 5,
  byrow = TRUE
)

# Set row and column names
categories <- c("None", "Mild", "Moderate", "Severe", "Extreme")
rownames(data_matrix) <- categories
colnames(data_matrix) <- categories

# Display the contingency table
print("Contingency Table:")
print(data_matrix)

# (i) Calculate Unweighted Kappa statistic
kappa_unweighted <- Kappa(data_matrix, weights = "equal")
print("Unweighted Kappa Statistic:")
print(kappa_unweighted)

# (ii) Calculate Weighted Kappa statistic (using default squared/Fleiss-Cohen weights)
kappa_weighted <- Kappa(data_matrix, weights = "Fleiss-Cohen")
print("Weighted Kappa Statistic:")
print(kappa_weighted)

# Interpretation helper function based on Landis and Koch guidelines
interpret_kappa <- function(k) {
  if (k < 0) {
    return("Poor agreement (less than chance)")
  } else if (k <= 0.20) {
    return("Slight agreement")
  } else if (k <= 0.40) {
    return("Fair agreement")
  } else if (k <= 0.60) {
    return("Moderate agreement")
  } else if (k <= 0.80) {
    return("Substantial agreement")
  } else {
    return("Almost perfect agreement")
  }
}

# Extract values and print interpretations
unweighted_val <- kappa_unweighted$Unweighted[1]
weighted_val <- kappa_weighted$Weighted[1]

cat("\n--- Interpretation of Results ---\n")
cat(sprintf("(i) Unweighted Kappa = %.4f -> %s\n", unweighted_val, interpret_kappa(unweighted_val)))
cat(sprintf("(ii) Weighted Kappa = %.4f -> %s\n", weighted_val, interpret_kappa(weighted_val)))