rrankingranking-functionsweighting

How to compute a weighted ranking score?


Given the output of a ranking question:

df <- structure(list(rank1 = c("A", "NA", "C", "B", "A"), rank2 = c("B", 
"NA", "A", "A", "B"), rank3 = c("C", "NA", "B", "C", "NA"), rank4 = c("D", 
"NA", "E", "D", "NA"), rank5 = c("E", "NA", "D", "E", "NA")), .Names = c("rank1", 
 "rank2", "rank3", "rank4", "rank5"), class = "data.frame", row.names = c("1", 
 "2", "3", "4", "5"))


  rank1 rank2 rank3 rank4 rank5
1     A     B     C     D     E
2    NA    NA    NA    NA    NA
3     C     A     B     E     D
4     B     A     C     D     E
5     A     B    NA    NA    NA

I want to calculate a ranking score for each letter = the number of counts for each ranking on a letter * weighting of each rank (rank1 = 5 points, rank2 = 4 points,..., rank5 = 1 point) / total response count.

To get the number of counts for each rank by letter I used this:

table(unlist(data1), c(col(data1)))

     1 2 3 4 5
  A  2 2 0 0 0
  B  1 2 1 0 0
  C  1 0 2 0 0
  D  0 0 0 2 1
  E  0 0 0 1 2
  NA 1 1 2 2 2

So now I would like to calculate the score for each letter (e.g. for A = (2 * 5 + 2 * 4) / 4) I don't know how to get to the total response count and then how to create a function to calculate the ranking score.


Solution

  • Using an apply function you can iterate over each row of the table, and then calculate the score

    apply(table(unlist(df), c(col(df))), 1, FUN = function(row){
      return((row[1] * 5 + row[2] * 4 + row[3] * 3 + row[4] * 2 + row[5] * 1) / sum(row))
    })
    
     A        B        C        D        E       NA 
    4.500000 4.000000 3.666667 1.666667 1.333333 2.625000 
    

    The fun part of the apply function passes the entire row to the function, then its just a case of multiply each corresponding element of the row by the weighting, then dividing by the total number of respondents for that row