Pairwise comparison analysis in R

71 Views Asked by At

I am seeking assistance with an R code that I've been trying to implement that I don't quite get to run.

Background

I have collected expert evaluations in the form of pairwise comparisons for four key challenges associated with forest resilience: Biodiversity Decline, Social Demand, Tree Species Suitability, and Risk of Disturbances. Each expert's evaluation is stored in a separate CSV file, and I have a total of 30 expert responses. The challenges are abbreviated as Biodivdecline, Socdemand, Treespsuit, and Riskdisturb in the raw data.

Here is an example matrix of my pairwise comparison from one expert:

;Biodivdecline;Socdemand;Treespsuit;Riskdisturb

Biodivdecline;1;1;1;2

Socdemand;1;1;1/2;1

Treespsuit;1;2;1;1

Riskdisturb;1/2;1;1;1

Code Functionality:
The R code provided aims to perform the following tasks:

  • Set the working directory.
  • Install and load necessary R packages (tidyverse, expss).
  • Define a function (fractions_to_decimal) to convert fractions to decimal numbers in the raw data.
  • Load the 30 CSV files, normalize the data, and convert fractions to decimals.
  • Calculate average ratings for each challenge across all experts.
  • Perform a consistency check using the Eigenvalue method with a 10% threshold.
  • Visualize the challenges' importance across all experts using a box plot.
  • Request for Help:

I have been encountering challenges in running the code smoothly, and I believe that there might be room for improvement. If you could spare some time to review the code and help identify potential issues or suggest improvements, I would greatly appreciate it.

Environment: I am using R

Goal

My ultimate goal is to prioritize these challenges based on expert evaluations and visualize the importance of each challenge across all experts.

I have attached the code below for your reference. Any guidance or suggestions would be immensely helpful.

# Install required packages
if (!requireNamespace("tidyverse", quietly = TRUE)) {
  install.packages("tidyverse")
}
if (!requireNamespace("expss", quietly = TRUE)) {
  install.packages("expss")
}
# Load required libraries
library(tidyverse)
library(expss)
  
# Function to convert fractions to decimal numbers
fractions_to_decimal <- function(matrix) {
  matrix <- as.matrix(matrix)
  numeric_matrix <- matrix(0, nrow = nrow(matrix), ncol = ncol(matrix))
  
  for (i in 1:nrow(matrix)) {
    for (j in 1:ncol(matrix)) {
      cell_value <- matrix[i, j]
      if (!is.na(cell_value) && grepl("/", cell_value)) {
        fraction_parts <- strsplit(cell_value, "/")[[1]]
        numerator <- as.numeric(fraction_parts[1])
        denominator <- as.numeric(fraction_parts[2])
        numeric_matrix[i, j] <- numerator / denominator
      } else {
        numeric_matrix[i, j] <- as.numeric(cell_value)
      }
    }
  }
  
  return(numeric_matrix)
}

# Set working directory
setwd("C:/Users/bs102/Documents/Resonate/Task 5.2/Data analysis_ R Studio/working_directory")

# Step 2: Load 30 CSV files with expert evaluations
file_names <- list.files(pattern = "^response_finland_Q1_\\d+\\.csv$")
expert_responses <- lapply(file_names, function(file) {
  read.csv(file, sep = ";", dec = ".", na.strings = "NA") %>%
    fractions_to_decimal()
})

# Step 3: Normalize individual matrices
normalized_matrices <- lapply(expert_responses, function(matrix) {
  # Convert NA values to a neutral score (e.g., 1)
  matrix[is.na(matrix)] <- 1
  # Row-wise normalization
  normalized_matrix <- matrix / colSums(matrix)
  return(normalized_matrix)
})

# Step 4: Calculate average ratings for each challenge across all experts
average_ratings <- Reduce(`+`, normalized_matrices) / length(normalized_matrices)

# Step 5: Consistency check using Eigenvalue method
consistency_check <- function(matrix) {
  pairwise_comparison <- as.pairwise(matrix, reverse = TRUE)
  eigenvalues <- eigen(pairwise_comparison)$values
  consistency_ratio <- max(eigenvalues) / sum(eigenvalues)
  return(consistency_ratio)
}

consistency_ratios <- sapply(normalized_matrices, consistency_check)

# Check if consistency ratio exceeds the 10% threshold
inconsistent_experts <- which(consistency_ratios > 0.10)

if (length(inconsistent_experts) > 0) {
  cat("Inconsistent experts:", inconsistent_experts, "\n")
} else {
  cat("All experts have consistent comparisons.\n")
}

# Step 6: Visualization - Box plot of challenge importance
challenge_names <- colnames(average_ratings)
boxplot(t(average_ratings), col = "lightblue", main = "Challenge Importance Across Experts",
        ylab = "Normalized Importance", names = challenge_names)

# Save the box plot as an image if needed
# savePlot("boxplot_challenge_importance.png")
0

There are 0 best solutions below