0

I have dataset like this:

Value 
  5    
  4
  2
  1   

I want the largest value to have the smallest rank while the lowest value to have the highest rank. In this dataset, Value=1 will recode to 5 while Value=5 will recode to 1. However, due to the missing Value=3 in my dataset, by using the rank function rank(-Value), I only managed to get this

Value Rank 
  5    1   
  4    2
  2    3
  1    4   

Is there any way in R to get something like this?

Value Rank 
  5    1   
  4    2
  2    4
  1    5   
CHONG
  • 373
  • 1
  • 5
  • 13

2 Answers2

0

Try it like this:

df <- data.frame(Value = c(5, 4, 2, 1))
df$fact <- as.factor(df$Value)
df$Rank <- as.numeric(rev(levels(df$fact)))[df$fact]


> (df <- df[, -2])
  Value Rank
1     5    1
2     4    2
3     2    4
4     1    5
J. Win.
  • 6,662
  • 7
  • 34
  • 52
0

You can do this by finding the max and min values of your vector and then searching for the index within a complete number set between the max and min.

v <- c(5,4,2)
x <- min(v)
y <- max(v)
x:y
match(v,x:y)
[1] 4 3 1

Using the levels of a factor as J.Win. suggests will work as long as there is a 1 in your vector but otherwise, the highest value will not have a rank of 1. Sorry, I do not have enough reputation to add this as a comment.

Dylan S.
  • 359
  • 4
  • 15