# Title: Simple Analytic Hierarchy Process function # Author: James Keirstead # Date: 5 August 2009 # Installation # -------------------- # To install the script, copy and paste its contents into an R session # (www.r-project.org) or load it using the "source" command. # # Usage # -------------------- # To call the function, use something like: # # categories <- c("Apples","Oranges","Pears") # ahp <- AHP(categories) # # The script will ask you to compare pairs of categories. Answer # each question with a clear goal in your mind (e.g. which fruit # is tastiest) and use scores from 1,3,5,7,9 or 1, 1/3, 1/5, 1/7, 1/9 # where 1 = equal, 3 = moderately preferred, 5 = strongly preferred, # 7 = very strongly preferred, 9 = extremely preferred. # # Example: If A is moderately preferred to B, answer as follows: # # Compare A to B: 3 # or Compare B to A: 1/3 # # Output # -------------------- # Using the above example, the results can be accessed as follows: # # Weights of each category: ahp$weight # Consistency ratio: ahp$cr # # The weights should only be used if the consistency ratio is less # than or equal to 0.10; otherwise repeat the analysis. # # For more information # -------------------- # http://www.academicproductivity.com/2009/testing-the-general-model-of-productivity AHP <- function(x) { n <- length(x) mat <- diag(n) # Randomly mix the categories comb <- combn(x,2) o <- sample(1:ncol(comb)) for (i in o) { c <- which(x==comb[1,i]) r <- which(x==comb[2,i]) val <- readline(paste("Compare",x[r],"to",x[c]," 1-9: ")) mat[c,r] <- eval(parse(text=val)) } mat <- t(mat) + mat mat[upper.tri(mat)] <- 1/mat[upper.tri(mat)] diag(mat) <- 1 result <- eigen (mat) val <- as.numeric(result$values[1]) vec <- as.numeric(result$vectors[,1]) weight <- vec /sum(vec) ci <- (val-n)/(n-1) cr <- ci/c(0,0,0.58,0.9,1.12,1.24,1.32,1.41,1.45,1.49,1.51,1.53)[n] if (ci > 0.1 || cr > 0.1) { cat("\n CI = ",ci,", CR = ", cr, "\n", sep="") print(mat) W <- outer(weight, weight,"/") print(W) print(mat-W) } return (list (mat=mat, lambda=val,vec=vec, weight=weight,ci=ci,cr=cr)) }