vendredi 21 août 2015

Create new variable showing whether values in variable x is larger than values in variables y and z: handling ties.

I have three variables and want to create a new variable indicating if the first variable (x) is largest (=1) or not (=0). If there is a tie between two variables this should be indicated as 0.5; and if there are a tie between all three variables this should be indicated with 0.33. Here are example data

 x= c(5, 1, 5, 5, 4)
 y= c(1, 1, 5, 5, 5)
 z= c(1, 2, 4, 5, 5)
 data <-data.frame(x, y, z)

This is how it should be in the end

 correct = c(1, 0, 0.5, 0.333, 0)
 datafinal <- data.frame(x, y, z, correct)
 datafinal

> datafinal
   x y z correct
 1 5 1 1   1.000
 2 1 1 2   0.000
 3 5 5 4   0.500
 4 5 5 5   0.333
 5 4 5 5   0.000

I have started with the below; however, when it is a tie it appears to randomly assign a number which makes me think I am on the wrong path?

  data$correct <- ifelse(max.col(data)==1, 1, 0)

Very grateful for any help. Gorp

Aucun commentaire:

Enregistrer un commentaire