Lawrence Chillrud
Lawrence Chillrud

Reputation: 31

rank() function in R is ranking objects with floating points rather than integers

I'm quite new to R so this may seem quite trivial to many experienced programmers, sorry in advance!

I've got a numeric vector of length 8 that looks like this:

data <- c(45, 67, 23, 24, 5, 23, 45, 23)

When I type in: rank(data), R returns: [1] 6.5 8.0 3.0 5.0 1.0 3.0 6.5 3.0

However with my (very basic) understanding of rank, I expect R to return to me only whole numbers... such as:

[1] 6 8 2 5 1 3 7 4

How can rank() tell me the first element in data has a floating point ranking rather than a whole number ranking? Is it because there are values in data that are repeated and so rank() is trying to handle ties in a way that I am not expecting? If so, please tell me how I can fix this so I can get output that looks like what I previously expected. Also, any information on how rank() deals with NA values would be much appreciated. A basic description on rank() and what bells and whistles can be used would be fantastic! I've looked for videos on youtube and searched stackoverflow to no avail! Thanks so much.

Upvotes: 1

Views: 4732

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145825

From ?rank:

With some values equal (called ‘ties’), the argument ties.method determines the result at the corresponding indices. The "first" method results in a permutation with increasing values at each index set of ties. The "random" method puts these in random order whereas the default, "average", replaces them by their mean, and "max" and "min" replaces them by their maximum and minimum respectively, the latter being the typical sports ranking.

Sounds like you're using the default setting of "average" for tie breaking, which uses the mean, which is not necessarily an integer.

The built-in documentation should always be your first stop in looking for help. In this case (and most cases), it details all the "bells and whistles"---here there aren't many: just tie-handling and NA-handling. It also has examples at the bottom.

Upvotes: 8

Related Questions